简体   繁体   中英

Reading Text Files in FileSystemWatcher in C# getting Error of File already in Use by another resource

Hello I want to use FileSystemWatcher in C Sharp to watch for the text files coming in a folder Reading There Text and uploading Their text to a Web Server with a GET Request in C Sharp

but the problem is that when i try it and first time when some file opened it works fine but on second time when a file come to the directory it will show me that the file is already used by another application or the resource is not free its already allocated.

here is the small code for it

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Net;

namespace FileChangeNotifier
{
public partial class frmNotifier : Form
{
    private StringBuilder m_Sb;
    private bool m_bDirty;
    private System.IO.FileSystemWatcher m_Watcher;
    private bool m_bIsWatching;

    public frmNotifier()
    {
        InitializeComponent();
        m_Sb = new StringBuilder();
        m_bDirty = false;
        m_bIsWatching = false;
    }

    private void btnWatchFile_Click(object sender, EventArgs e)
    {
        if (m_bIsWatching)
        {
            m_bIsWatching = false;
            m_Watcher.EnableRaisingEvents = false;
            m_Watcher.Dispose();
            btnWatchFile.BackColor = Color.LightSkyBlue;
            btnWatchFile.Text = "Start Watching";

        }
        else
        {
            m_bIsWatching = true;
            btnWatchFile.BackColor = Color.Red;
            btnWatchFile.Text = "Stop Watching";

            m_Watcher = new System.IO.FileSystemWatcher();
            if (rdbDir.Checked)
            {
                m_Watcher.Filter = "*.*";
                m_Watcher.Path = txtFile.Text + "\\";
            }
            else
            {
                m_Watcher.Filter = txtFile.Text.Substring(txtFile.Text.LastIndexOf('\\') + 1);
                m_Watcher.Path = txtFile.Text.Substring(0, txtFile.Text.Length - m_Watcher.Filter.Length);
            }

            if (chkSubFolder.Checked)
            {
                m_Watcher.IncludeSubdirectories = true;
            }

            m_Watcher.NotifyFilter = NotifyFilters.LastAccess | NotifyFilters.LastWrite | NotifyFilters.FileName | NotifyFilters.DirectoryName;
            m_Watcher.Created += new FileSystemEventHandler(OnChanged);
            m_Watcher.EnableRaisingEvents = true;
        }
    }

    private void OnChanged(object sender, FileSystemEventArgs e)
    {
        if (!m_bDirty)
        {
            readFile(e.FullPath);
            m_Sb.Remove(0, m_Sb.Length);
            m_Sb.Append(e.FullPath);
            m_Sb.Append(" ");
            m_Sb.Append(e.ChangeType.ToString());
            m_Sb.Append("    ");
            m_Sb.Append(DateTime.Now.ToString());
            m_bDirty = true;
        }
    }


    private void readFile(String filename) {
        String line = "";
        if (File.Exists(filename))
        {
            try{
                StreamReader sr = new StreamReader(filename);

                //code for multiline reading but i need only one line so i am going to change he code
               /* while ((line = sr.ReadLine()) != null)
                {
                    MessageBox.Show(line);
                }
                */
                line = sr.ReadLine();
                MessageBox.Show(line);
                uploadDataToServer(line);
                sr.Close();
            } catch(IOException e){
                MessageBox.Show(e.Message);

            }

        }

    }

    private void uploadDataToServer(String data) {
        String url = "http://209.90.88.135/~lilprogr/?data="+data;

        HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);

        HttpWebResponse response = (HttpWebResponse)request.GetResponse();

        Stream resStream = response.GetResponseStream();
    }
}
}

To handle multiple change notifications, go here and look for @BaBu's answer.

Also,
If all you need is to read from the file,
Have you tried to open it in Shared Mode ?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM