[英]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.