CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 3 of 3

Thread: .NET StreamWriter Error

  1. #1
    Join Date
    Aug 2005
    Posts
    27

    .NET StreamWriter Error

    I have the following code to in my application but when I try to run the application I am getting the error

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

    //Function 1

    public void Function1()
    {
    StreamReader strmReader = new StreamReader(tempBatchFileName);
    StreamWriter strmWriter = new StreamWriter(BatchFileName);
    while(strmReader.Peek() != -1)
    {
    string currentLine = strmReader.ReadLine();
    strmWriter.WriteLine(currentLine);
    }
    strmReader.Close();
    strmWriter.Close();
    }


    //Function2

    public string Function2()
    {

    System.IO.StreamReader strm = System.IO.File.OpenText(BatchFileName);

    while(strm.Peek() != -1)
    {
    console.WriteLine(strm.ReadLine());
    }
    return "test";
    }


    Any idea whats causing this issue. I am closing it in the first Function but still not able to access it.

  2. #2
    Join Date
    Oct 2001
    Posts
    80

    Re: .NET StreamWriter Error

    I think you should put in Funciton1, before you close the streamwriter, strmWriter.Flush();

    This might not solve your problem, but it's a good programming to put it there.

  3. #3
    Join Date
    Mar 2004
    Location
    Prague, Czech Republic, EU
    Posts
    1,701

    Re: .NET StreamWriter Error

    In Function2, you doesn't close the strem. Genraly, it is recommended to use using statement to work with stream. See the example.

    Code:
    public void Function1()
    {
      using (
        StreamReader strmReader = new StreamReader(tempBatchFileName); 
        StreamWriter strmWriter = new StreamWriter(BatchFileName);
      ){
       while(strmReader.Peek() != -1)
      {
        string currentLine = strmReader.ReadLine();
        strmWriter.WriteLine(currentLine);
      }
    }
    But don't forget: the file can be opened (and holded) by totaly different process like Notepad. Also keep in mind: always Dispose() any object which is using external resources (like file). Using statement does it for you, but keep it in mind.
    • Make it run.
    • Make it right.
    • Make it fast.

    Don't hesitate to rate my post.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  


Windows Mobile Development Center


Click Here to Expand Forum to Full Width




On-Demand Webinars (sponsored)