我检查文件是否存在
if(!File.Exists(myPath))
{
File.Create(myPath);
}
Run Code Online (Sandbox Code Playgroud)
但是,当我StreamReader使用这个新创建的文件创建一个时,我得到一个错误说
该进程无法访问文件'[我的文件路径]',因为它正由另一个进程使用.
没有File.Close(myPath)我可以调用它以便它在创建后关闭,所以如何释放这个资源以便我可以在我的程序中稍后打开它?
Don*_*nut 149
File.Create(string)返回FileStream该类的实例.您可以Stream.Close()在此对象上调用该方法以关闭它并释放它正在使用的资源:
var myFile = File.Create(myPath);
myFile.Close();
Run Code Online (Sandbox Code Playgroud)
但是,由于FileStreamimplements IDisposable,您可以利用该using语句(通常是处理这种情况的首选方法).这将确保在您完成流时关闭并正确处理流:
using (var myFile = File.Create(myPath))
{
// interact with myFile here, it will be disposed automatically
}
Run Code Online (Sandbox Code Playgroud)
Mar*_*rio 49
该函数返回一个FileStream对象.因此,您可以使用它的返回值来打开StreamWriter或使用对象的正确方法关闭它:
File.Create(myPath).Close();
Run Code Online (Sandbox Code Playgroud)
原因是因为创建文件的方法返回了 FileStream。您应该将 FileStream 返回到变量中,或者在 File.Create 之后直接调用 close 方法。
最佳实践是让 using 块帮助您为此类任务实现 IDispose 模式。也许效果更好的方法是:
if(!File.Exists(myPath)){
using(FileStream fs = File.Create(myPath))
using(StreamWriter writer = new StreamWriter(fs)){
// do your work here
}
}
Run Code Online (Sandbox Code Playgroud)
小智 5
File.WriteAllText(file,content)
Run Code Online (Sandbox Code Playgroud)
创建写关闭
File.WriteAllBytes-- type binary
Run Code Online (Sandbox Code Playgroud)
:)
| 归档时间: |
|
| 查看次数: |
152448 次 |
| 最近记录: |