[英].NET File.Create , can't delete file afterwards
使用方法: System.IO.File.Create()
文件创建后,它仍然由进程使用,我无法删除它。
任何想法我怎么能更好地创建文件,应该是一个0byte文件,然后以某种方式关闭和处置?
JL,
您应该在using语句中包含对.Create的调用,以便正确关闭.Create返回的FileStream。 IE:
using (File.Create("path")){...}
Create方法不仅创建文件,还会打开它并返回可用于写入文件的FileStream对象。
您必须自己关闭文件,否则在垃圾收集器清理FileStream对象之前不会关闭它。
最简单的方法是使用Create方法返回的引用简单地关闭文件:
File.Create(fileName).Close();
nikmd23有简短的答案,答案很长: File.Create(...)
返回的FileStream
没有被确定性地处理,因此当你试图删除它时,它的文件句柄没有关闭。
正如nikmd23所说的那样, using
语句包装你的File.Create(...)
调用将确保关闭并处理流:
using (FileStream fs = File.Create(path)) {
// do anything with the stream if need-be...
}
File.Delete(path); //after it's been disposed of.
using(...)
块实际上只是编译器 - 糖:
FileStream fs = File.Create(path);
try {
// do anything with the stream if need-be...
}
finally {
fs.Dispose();
}
File.Delete(path)
using(FileStream f = File.Create(file_path))
{
// ... do something with file
f.Close();
}
“f.Close();” 行立即关闭文件。 如果不手动关闭,处置可能不会关闭它。
请参见System.IO.File.Create(String)
方法参数和返回值描述
参数
path类型:
System.String
要创建的文件的路径和名称。回报价值
键入:
System.IO.FileStream
FileStream
,提供对path中指定的文件的读/写访问权限。
FileStream
返回值用于IO访问创建的文件。 如果您对编写(或读取)新创建的文件不感兴趣,请关闭该流 。 这就是using
块确保的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.