我正在使用System.IO.File.Create
创建文件。 我没有使用流编写器进行写入,只是创建了它。
当应用程序尝试打开新创建的文件时,前端会出现服务器错误-即文件正在使用中。 然后垃圾回收似乎会在几分钟后将所有内容都清理掉。
现在我知道如果我使用Streamwriter,我必须关闭它。 创建文件是否也适用此规则?
我已经阅读到,打开一个StreamWriter到文件然后立即关闭它可以解决这个问题,但这似乎很麻烦。 是否有更简单的方法?
试一下这个:
System.IO.File.Create(FullFName).Close();
File.Create
返回一个 FileStream
。你应该这样使用它:
using (FileStream fs = File.Create(path))
{
//you can use the filstream here to put stuff in the file if you want to
}
创建该文件会打开一个FileStream
,从而将其锁定(File.Create
返回FileStream
)。
您必须关闭此流才能访问该文件。最好使用using
语句完成此操作:
using(FileStream fs = File.Create(path))
{
}
File.Create
时,会返回一个FileStream
。在你关闭流或FileStream
对象被垃圾回收器的终结器处理之前,它将保持打开和锁定状态。
FileStream
实现了IDisposable
接口,因此可以执行以下操作:using(FileStream fs = File.Create(filename))
{
// Do stuff like write to the file
}
using
语句是一种“语法糖”,它会导致编译器生成与以下代码在功能上等效的代码:FileStream fs = File.Create(filename)
try
{
// Do stuff like write to the file
}
finally
{
fs.Dispose();
}
Dispose
方法会在内部调用 Close
方法。我之前使用的是:System.IO.File.Create(sFullFileName);
上述的.Create
方法没有关闭文件。
现在我使用:System.IO.File.WriteAllText(sFullFileName, "上传中");
这种方法会创建并关闭文件(注意:我在文件中放了一个字符串“上传中”,但我相信string.Empty
也可以工作)。
Create
方法将返回一个文件句柄。在重新使用该文件之前,应关闭文件句柄。请参阅 MSDN 文章 File.Create Method (String) 以获取详细信息。
摘要:
此方法创建的 FileStream 对象具有默认的 FileShare 值 None;直到关闭原始文件句柄之前,没有其他进程或代码可以访问创建的文件。
Dispose()
替换Close()
,或者更好的方法是使用using
语句。 - phoenix