C# 文件保存问题
本文关键字:问题 保存 文件 | 更新日期: 2023-09-27 18:36:53
我正在尝试将所有这些字符串放在一起,以便我的程序保存文档。没什么好看的。但是每次我去调试中保存文件时,它都会创建一个以该文件命名的文件夹,而不执行任何其他操作。我觉得这是一个简单的问题,但我找不到解决方法。请帮忙!
我的代码
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;