locked
The process cannot access the file <fileName> because it is being used by another process. RRS feed

  • General discussion

  • Hi Friends,

    I am getting the exception "The process cannot access the file 'C:\Users\<UserName>\Desktop\product.txt' because it is being used by another process."

    Below is the code snippet.

    private void button1_Click(object sender, EventArgs e)

    {

    string lines = string.Empty;
            switch(num)
                {
                    case 0:
                        lines = "a";
                        break;
                    case 1:
                        lines = "ab";
                            break;
                    case 2:
                        lines ="abc";
                        break;
                    case 3:
                        lines = "abcd";
                        break;
                    case 4:
                        lines = "abcde";
                        break;
                    case 5:
                        lines = "abcdef";
                        break;
                    default:
                        lines = "xyz";
                        break;
                }
                System.IO.StreamWriter file = new System.IO.StreamWriter("C:/Users/<UserName>/Desktop/product.txt");
                file.BaseStream.Seek(0, SeekOrigin.End);
                file.Write(lines);
                file.Close();
                num++;

    }

    private void InitializeComponent()
     {
    FileSystemWatcher _fileWatcher = new FileSystemWatcher();
            _fileWatcher.Path = "C:/Users/<UserName>/Desktop";
             _fileWatcher.NotifyFilter = NotifyFilters.LastWrite;
             _fileWatcher.Filter = "product.txt";
             _fileWatcher.Changed += new FileSystemEventHandler(OnChanged);
             _fileWatcher.EnableRaisingEvents = true;

    }

    private void OnChanged(object source, FileSystemEventArgs e)
    {
          string text1 = System.IO.File.ReadAllText(@"C:/Users/<UserName>/Desktop/product.txt");
          if (!string.IsNullOrEmpty(text1) && text != text1)
           {
                    string name = string.Empty;
                    int screenWidth = Screen.GetBounds(new Point(0, 0)).Width;
                    int screenHeight = Screen.GetBounds(new Point(0, 0)).Height;
                    Bitmap bmpScreenShot = new Bitmap(screenWidth, screenHeight);
                    Graphics gfx = Graphics.FromImage((Image)bmpScreenShot);
                    gfx.CopyFromScreen(0, 0, 0, 0, new Size(screenWidth, screenHeight));
                    if (!string.IsNullOrEmpty(text))
                    {
                        name = "C:/Users/<UserName>/Desktop/" + text1.Replace(text, "");
                    }
                    else
                    {
                        name = "C:/Users/<UserName>/Desktop/" + text1;
                    }
                    bmpScreenShot.Save(name + ".jpg", ImageFormat.Jpeg);
                    text = text1;
               }
    }

    It is throwing above mentioned exception at the line "string text1 = System.IO.File.ReadAllText(@"C:/Users/<UserName>/Desktop/product.txt");".

    What I want to do is, one text file will be changed by an app and whenever that file will be changed then form application will get notified and will take the printScreen and save that with a specific name to a specific location.

    Above mentioned code is a sample code, if anything is wrong in logic then also you can mention about that but main problem is why it is not able to access that file?

    Thanks

    Tuesday, June 3, 2014 12:22 PM

All replies

  • Hi,

    That is due to you didn't use Dispose() after you finished using that streamwriter.

    Dispose() is to releases all resources used by the TextWriter object, since you didn't call that method, the the resources are still being used, then when you call that line, it will get that exception.

    To solve this issue, we could use Using like the sample of the following document .

    StreamWriter Class (System.IO)

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.IO;
    
    namespace StreamReadWrite
    {
        class Program
        {
            static void Main(string[] args)
            {
                // Get the directories currently on the C drive.
                DirectoryInfo[] cDirs = new DirectoryInfo(@"c:\").GetDirectories();
    
                // Write each directory name to a file. 
                using (StreamWriter sw = new StreamWriter("CDriveDirs.txt"))
                {
                    foreach (DirectoryInfo dir in cDirs)
                    {
                        sw.WriteLine(dir.Name);
    
                    }
                }
    
                // Read and show each line from the file. 
                string line = "";
                using (StreamReader sr = new StreamReader("CDriveDirs.txt"))
                {
                    while ((line = sr.ReadLine()) != null)
                    {
                        Console.WriteLine(line);
                    }
                }
            }
        }
    }

    Regards.


    We are trying to better understand customer views on social support experience, so your participation in this interview project would be greatly appreciated if you have time. Thanks for helping make community forums a great place.
    Click HERE to participate the survey.

    Wednesday, June 4, 2014 2:40 AM
  • Thanks Carl.

    I used

    using(Stream filestream = await file.OpenStreamForWriteAsync())
    using (StreamWriter writer = new StreamWriter(filestream))
    {
    await writer.WriteAsync(contents);
    writer.Dispose();
    }

    And It worked for me.

    Thanks Again.

    Thursday, June 5, 2014 12:32 PM