关闭c#中一段代码使用的进程

本文关键字:代码 进程 一段 关闭 | 更新日期: 2023-09-27 18:14:14

我有这个代码

path = textBox1.Text;
dir = @"C:'htmlcsseditor'" + path + ".html";
System.IO.File.Create(dir);

但是当我尝试在文件上写时,调试告诉我该文件被另一个进程使用;如何关闭使用该文件的进程?由于

关闭c#中一段代码使用的进程

你应该处理你的文件,因为它一直是打开的。

path = textBox1.Text;
dir = @"C:'htmlcsseditor'" + path + ".html";
using (System.IO.File.Create(dir)) {} // or System.IO.File.Create(dir).Dispose()

这个方法创建的FileStream对象有一个默认的FileShareNone的值;没有其他进程或代码可以访问创建的文件直到原文件句柄被关闭。

using (FileStream fs = File.Create(path))
{
    Byte[] info = new UTF8Encoding(true).GetBytes("This is some text in the file.");
    // Add some information to the file.
    fs.Write(info, 0, info.Length);
}
下面是如何创建文件并在文件中写入一些文本。当您离开using块时,您正在关闭进程。在使用结束时称为Dispose()方法,该方法正在释放资源。