Skip to main content
 首页 » 编程设计

c#之"The process cannot access the file because it is being used by another process "

2024年08月06日33kuangbin

我正在使用 Windows 窗体在 C# 中编写我的应用程序。我想执行 CMD 命令,将结果保存到文本文件,然后在我的程序中打开这个文件来解析并最终使用我需要的值。不幸的是,当我运行它时,CMD 写“该进程无法访问该文件,因为它正在被另一个进程使用。我阅读了一些有关 FileStream 的内容,但如果我没记错的话,它只能在 .NET 应用程序中使用。我该怎么办解决我的问题?

我使用了以下部分代码。可能其中一个是问题:

  private void exec_cmd(string arguments) 
    { 
        System.Diagnostics.Process process = new System.Diagnostics.Process(); 
        System.Diagnostics.ProcessStartInfo startInfo = new System.Diagnostics.ProcessStartInfo(); 
        startInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Normal; 
        startInfo.FileName = "cmd.exe"; 
        startInfo.Arguments = arguments; 
        process.StartInfo = startInfo; 
        process.Start(); 
    } 
 
    public void countValues(string fileName){ 
        exec_cmd("/C hd.exe "+fileName+" > out.txt"); 
    } 
 
    private int numberOfFrames() { 
 
        System.IO.StreamReader file = new System.IO.StreamReader("out.txt"); 
        string[] dane; 
 
        int ile = 0; 
        dane = new string[ile]; 
 
        while (file.EndOfStream) 
        { 
            file.ReadLine(); 
            ile++; 
        } 
        return ile - 1; 
    } 

请您参考如下方法:

完成流阅读器后,您必须添加

file.Close();

关闭流,然后可以从其他地方安全地使用它