簡體   English   中英

C#文件保存問題

[英]C# File saving issues

我試圖將所有這些字符串放到程序保存文件的路徑中。 但是每次我在調試時保存文件時,它將創建一個以該文件命名的文件夾,並且什么也不做。 我覺得這是一個簡單的問題,但我找不到解決方法。 請幫助!

我的代碼

 private void btnSave_Click(object sender, EventArgs e)
 {
   string strNotes = rtbNotes.Text.ToString();
   string strUser = txtUser.Text.ToString() + "\\";
   string strClass = txtClass.Text.ToString() + "\\";
   string strDate = DateTime.Today.Date.ToString("dd-MM-yyyy");
   string strLocation = "C:\\Users\\My\\Desktop\\Notes\\";
   string strType = txtType.Text.ToString();
   string strFile = strLocation + strUser + strClass + strDate;
   string subPath = strFile + "." + strType;
    bool isExists = System.IO.Directory.Exists(subPath);
    if (!isExists)
        System.IO.Directory.CreateDirectory(subPath);
   System.IO.File.WriteAllText(strFile, strNotes);
}

首先,您的strLocation路徑無效:

C:\\用戶\\我的\\桌面\\注意事項\\

其次要傳遞整個文件路徑(包括文件名/擴展名)到Directory.Exists所以它的實際檢查,看看,看看是否存在一個名為“12/12 / 13.txt” 文件夾 (你應該簡單地將文件夾路徑)。

然后,您嘗試寫入文件,但傳遞應該是目錄路徑的內容...

您是否正在使用調試器來逐步執行代碼? 這會有所幫助。

private void button1_Click(object sender, EventArgs e)
        {
            string strNotes = "Some test notes.";
            string strUser = "someuser" + "\\";
            string strClass = "SomeClass" + "\\";
            string strDate = DateTime.Today.Date.ToString("dd-MM-yyyy");
            string strLocation = "C:\\Users\\My\\Desktop\\Notes\\";
            string strType = "txt";
            string strFile = strLocation + strUser + strClass + strDate; // ... this is: C:\Users\My\Desktop\Notes\
            string subPath = strFile + "." + strType; // .. this is: C:\Users\My\Desktop\Notes\someuser\SomeClass\26-10-2013.txt
            bool isExists = System.IO.Directory.Exists(subPath); // ... Checks directory: C:\Users\My\Desktop\Notes\ exists...
            if (!isExists)
                System.IO.Directory.CreateDirectory(subPath); // ... Creates directory:  C:\Users\My\Desktop\Notes\ ...
            System.IO.File.WriteAllText(strFile, strNotes); // ... Writes file: this is: C:\Users\My\Desktop\Notes\26-10-2013 ...
        }

您需要調試並觀察subPath的值。 似乎已將其設置為所需文件名的值,但沒有擴展名。

我想你應該有

string subPath = strLocation + strUser + strClass + strDate;
string strFile = subPath + "." + strType;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM