基本上我想创建一个文件,如果不存在然后向它写入消息。
if (!File.Exists(filePath + fileName))
File.Create(filePath + fileName);
StreamWriter sr = new StreamWriter(filePath + fileName,false);
如何处理这个错误?
该进程无法访问文件“c:\blahblah”,因为它正被另一个进程使用。
File.Create
打开一个FileStream
(http://msdn.microsoft.com/en-us/library/d62kzs03.aspx)。
由于您没有处理它,因此如果从其他句柄(即 otherFileStream
或 whole StreamWriter
)执行这些操作,文件将保持锁定,并且由于这种情况,对文件的后续访问将失败。
此代码演示了您应该如何使用以下IDisposable
对象FileStream
:
if (!File.Exists(filePath + fileName))
{
File.Create(filePath + fileName).Dispose();
using(StreamWriter sr = new StreamWriter(filePath + fileName,false))
{
}
}
为什么不直接使用StreamWriter
接受文件名的构造函数呢?
StreamWriter sr = new StreamWriter(filePath + fileName);
来自MSDN:
path 参数可以是文件名,包括通用命名约定 (UNC) 共享上的文件。如果文件存在,则覆盖;否则,将创建一个新文件。
非常次要的一点,但您可以考虑Path.Combine
在连接文件名和文件夹路径时使用。
通过使用单一方法创建和打开文件来简化代码:
using (FileStream fs = File.OpenWrite(path))
{
Byte[] info = new UTF8Encoding(true)
.GetBytes("This is to test the OpenWrite method.");
fs.Write(info, 0, info.Length);
}
MSDN:(File.OpenWrite 方法)
打开现有文件或创建新文件以进行写入。