Search code examples
c#winformsvisual-studio-2010filestreamiostream

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


I'm writing my application in C# using Windows Form. I'd like to execute CMD command, save result to textfile and then open this file in my program to parse and finally use values what I need. Unfortunately, when I run it CMD write "The process cannot access the file because it is being used by another process. I read something about FileStream, but If I am not mistaken it can be use only in .NET applications. What should I do to fix my problem?

I use the following parts of code. Probably in one of them is a problem:

  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;
    }

Solution

  • when finishing with your stream reader, you have to add

    file.Close();

    to close the stream, then can use it from other places safely