Click here to Skip to main content
15,920,005 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I've a c# console application. I am trying to watch a usb file activities using FileSystemWatcher, If there is any file change is done then the event is triggered and my file content will be encoded into base64 format and display it in console.Now its showing an IOException like
The process cannot access F:\MyService.InstallLogI because it is being used by another process.


What I have tried:

C#
class Program
    {
        static FileSystemWatcher watcher;
        static void Main(string[] args)
        {
            var drives = DriveInfo.GetDrives();
            
            foreach (var drive in drives)
            {
                if (drive.DriveType == DriveType.Removable)
                {
                    Console.WriteLine(drive.Name);
                    watch(drive.Name);
                }
            }

        }
        static void watch(String path)
        {
            
            watcher = new FileSystemWatcher();

            watcher.Path = path;//assigning path to be watched
            watcher.EnableRaisingEvents = true;//make sure watcher will raise event in case of change in folder.
            watcher.IncludeSubdirectories = true;//make sure watcher will look into subfolders as well.
            watcher.Filter = "*.*"; //watcher should monitor all types of file.

            watcher.Created += watcher_Created; //register event to be called when a file is created in specified path
            watcher.Changed += watcher_Changed;//register event to be called when a file is updated in specified path
            watcher.Deleted += watcher_Deleted;//register event to be called when a file is deleted in specified path

           // watcher.Created += new FileSystemEventHandler(watcher_Changed);


            while (true) ;//run infinite loop so program doesn't terminate untill we force it.
        }

        static void watcher_Deleted(object sender, FileSystemEventArgs e)
        {
            Console.WriteLine("File : " + e.FullPath + " is deleted.");
        }

        static void watcher_Changed(object sender, FileSystemEventArgs e)
        {
            Console.WriteLine("File : " + e.FullPath + " is updated.");

            watcher.EnableRaisingEvents = false;

            try
            {
                if (!string.IsNullOrEmpty(e.FullPath))
                {

                    FileStream fs = new FileStream(e.FullPath, FileMode.Open, FileAccess.Read);
                    byte[] filebytes = new byte[fs.Length];
                    fs.Read(filebytes, 0, Convert.ToInt32(fs.Length));
                    string encodedData = Convert.ToBase64String(filebytes, Base64FormattingOptions.InsertLineBreaks);
                    Console.WriteLine(encodedData);

                    // File.WriteAllText(e.FullPath, encodedData);


                }

              }
            catch (Exception excep)
            {
                Console.WriteLine(excep.Message.ToString());
                //Thread.Sleep(100);
            }


            //watcher.EnableRaisingEvents = true;
        }

        static void watcher_Created(object sender, FileSystemEventArgs e)
        {
            Console.WriteLine("File : " + e.FullPath + " is created.");
           // System.Windows.Forms.Clipboard.Clear();

        }
 
    }
Posted
Updated 5-Apr-16 12:33pm
v2

The FileSystemWatcher will notify you when the file is changed but it has no idea if the writer of the file is done with it. Changes can be reported while the other application is still making them!

Your code has to try to open the file and if it fails, wait a bit and try again. It's up to you if you want to keep waiting indefinitely or just give up after a certain amount of time or number of tries.
 
Share this answer
 
Um...
C#
if (!string.IsNullOrEmpty(e.FullPath))
    {
    FileStream fs = new FileStream(e.FullPath, FileMode.Open, FileAccess.Read);
    byte[] filebytes = new byte[fs.Length];
    fs.Read(filebytes, 0, Convert.ToInt32(fs.Length));
    string encodedData = Convert.ToBase64String(filebytes, Base64FormattingOptions.InsertLineBreaks);
    Console.WriteLine(encodedData);
    // File.WriteAllText(e.FullPath, encodedData);
    }

You don't close the file - so the next time you try to access it, it's still open! It won't get closed until the Garbage collector gets kicked in - next week, maybe - to clean up after you.
Try a using block:
C#
if (!string.IsNullOrEmpty(e.FullPath))
    {
    using (FileStream fs = new FileStream(e.FullPath, FileMode.Open, FileAccess.Read))
        {
        byte[] filebytes = new byte[fs.Length];
        fs.Read(filebytes, 0, Convert.ToInt32(fs.Length));
        string encodedData = Convert.ToBase64String(filebytes, Base64FormattingOptions.InsertLineBreaks);
        Console.WriteLine(encodedData);
        // File.WriteAllText(e.FullPath, encodedData);
        }
    }
And it will be Closed and Disposed when it goes out of scope.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900