2013-10-26 153 views
1

我试图把所有这些字符串放在一起放到我的程序保存文档的路径中。没什么奇特的。但每次我在调试时保存文件时,它都会创建一个以该文件命名的文件夹,而不会执行其他任何操作。我觉得这是一个简单的问题,但我无法找到如何解决它。请帮助!C#文件保存问题

我的代码

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); 
} 
+0

您是否检查路径结果? subPath看起来像一个文件不是目录 – Sam

+0

此代码应创建一个全名+类型的目录。然后,它应该创建一个没有包含strNotes扩展名的文件。 (除非发生错误) – 2013-10-26 01:34:23

回答

1

首先,你strLocation路径无效:

C:\用户\我的\桌面\ NOTES \

其次要传递整个文件路径(包括文件名/扩展名)到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 ... 
     } 
+0

实际上,我认为'strFile'不是一个目录,而是一个缺少扩展名的文件。 – 2013-10-26 01:38:16

+0

啊是的..好点...我从调试器复制和粘贴文件夹路径,编辑! – BenjaminPaul

+0

我像你说的那样经历过它,改变了写和创建文件夹字符串,它的工作!非常感谢! –

0

你需要调试,看子路径的价值。它看起来像被设置为你想要的文件名的值,但没有扩展名。

我想你应该有

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