Search code examples
c#wpffilesystemwatchersystem.io.file

FileSystemWatcher C# - cannot access file because it is being used by another process


I'm using FileSystemWatcher to detect directory changes, and after that I read file content and insert it to database.

Here's my code:

private FileSystemWatcher _watcher;

public MainWindow()
{
    try
    {
        InitializeComponent();

        GetFiles();

        //Task.Factory.StartNew(() => GetFiles())
        //   .ContinueWith(task =>
        //   {
        //   }, System.Threading.CancellationToken.None, TaskContinuationOptions.None, TaskScheduler.FromCurrentSynchronizationContext());
    }
    catch(Exception ex)
    {
        //..
    }
}

public bool GetFiles()
{
    _watcher = new FileSystemWatcher(Globals.iniFilesPath, "*.ini");
    _watcher.Created += FileCreated;
    _watcher.IncludeSubdirectories = false;
    _watcher.EnableRaisingEvents = true;
    return true;
}

private void FileCreated(object sender, FileSystemEventArgs e)
{
    try
    {
        string fileName = Path.GetFileNameWithoutExtension(e.FullPath);

        if (!String.IsNullOrEmpty(fileName))
        {
            string[] content = File.ReadAllLines(e.FullPath);
            string[] newStringArray = content.Select(s => s.Substring(s.LastIndexOf('=') + 1)).ToArray();

            ChargingStationFile csf = new Product
            {
                Quantity = Convert.ToDecimal(newStringArray[1]),
                Amount = Convert.ToDecimal(newStringArray[2]),
                Price = Convert.ToDecimal(newStringArray[3]),
                FileName = fileName
            };

            ProductController.Instance.Save(csf);
        }
    }
    catch (Exception ex)
    {
        MessageBox.Show(ex.Message);
    }
}

If I run this code with CTRL+F5 I received this message:

enter image description here

But If I go with F5 (Debugging mode) than I receive this and not this error about cannot access process and item is sucessfully saved. This is confusing me really..

Should I dispose watcher? or something like that? Maybe I'm missing something here? enter image description here

This is first time I'm using FileSystemWatcher, obliviously something is really wrong here..

P.S I've found out that this line is causing an exception:

string[] content = File.ReadAllLines(e.FullPath);

how come?

Thanks guys

Cheers


Solution

  • File.ReadAllLines() cannot access the file when it is open for writing in another application but you can use a FileStream and StreamReader instead.

    Replace string[] content = File.ReadAllLines(e.FullPath); with the following code and you should be able to read the contents of the file regardless of whether it is open in another application:

    List<string> content = new List<string>();
    using (FileStream stream = new FileStream(e.FullPath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
    using (StreamReader sr = new StreamReader(stream))
    {
        while (!sr.EndOfStream)
            content.Add(sr.ReadLine());
    }