【问题标题】:Close process used by a piece of code in c#c#中一段代码使用的关闭进程
【发布时间】:2016-10-22 09:53:51
【问题描述】:

我有这个代码

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

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

【问题讨论】:

  • 检查我的答案,如果有什么不清楚的地方告诉我

标签: c# file process directory


【解决方案1】:

您应该处置您的文件,因为它一直处于打开状态。

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

【讨论】:

    【解决方案2】:

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

    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() 方法释放资源。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-06-09
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多