1

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;
    }
John Saunders
  • 160,644
  • 26
  • 247
  • 397
Robert
  • 140
  • 1
  • 8
  • you should use a "using" statement when dealing with a StreamReader...this will automatically close the file when it is done withit..other wise you get a file locked error or close the file yourself. – SuncoastOwner Dec 22 '14 at 01:50
  • I have edited your title. Please see, "[Should questions include “tags” in their titles?](http://meta.stackexchange.com/questions/19190/)", where the consensus is "no, they should not". – John Saunders Dec 22 '14 at 03:34

2 Answers2

2

when finishing with your stream reader, you have to add

file.Close();

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

chouaib
  • 2,763
  • 5
  • 20
  • 35
1

When calling process.Start(), your program do not wait hd.exe to end before execute next statement, just fire and forget. hd.exe still working and hold the output.txt while your program runs numberOfFrames() method immediately after call.

Add the following line after process.Start() to wait for exit

process.WaitForExit()

MSDN - Process.WaitForExit()

Btw, if you need to open the file as readonly (not read write), use File.OpenRead()

StreamReader streamReader = new StreamReader(File.OpenRead(file));
Eric
  • 5,675
  • 16
  • 24