hey, i have my streamreader code, but im running it in a filesystem watcher program,

once a certain file is seen, then read other files in the folder

so i basically have the filesystem watcher set up to wait for this certain file. then i know the reader tries to find a file but it cant. I think the problem must be the reader needing the folder directory that the filesystemwatcher is looking in, but i have no idea how.

for example, here is the code i have, how do i modify it to read files in the folder specified in "DestDir"

namespace ConsoleApplication1
{
    class process
    {
        private static string myString = string.Empty;
       

        static void Main(string[] args)
        {
           

            Run();
        }

        [PermissionSet(SecurityAction.Demand, Name = "FullTrust")]
        public static void Run()
        {
            string[] args = System.Environment.GetCommandLineArgs();

            // Create a new FileSystemWatcher and set its properties.
            FileSystemWatcher watcher = new FileSystemWatcher();
            
            string test1 = System.Configuration.ConfigurationSettings.AppSettings["DestDir"];
            
            
            watcher.Path = test1;//args[1];
            /* Watch for changes in LastAccess and LastWrite times, and
               the renaming of files or directories. */
            watcher.NotifyFilter = NotifyFilters.LastAccess | NotifyFilters.LastWrite
               | NotifyFilters.FileName | NotifyFilters.DirectoryName;
            // Only watch text files.
            watcher.Filter = "TransferComplete.*";

            // Add event handlers.
            //watcher.Changed += new FileSystemEventHandler(OnChanged);
            watcher.Created += new FileSystemEventHandler(OnChanged);
            //watcher.Deleted += new FileSystemEventHandler(OnChanged);
            //watcher.Renamed += new RenamedEventHandler(OnRenamed);

            // Begin watching.
            watcher.EnableRaisingEvents = true;

            // Wait for the user to quit the program.lol
            Console.WriteLine("Press \'q\' to quit the sample.");
            while (Console.Read() != 'q') ;
        }

        // Define the event handlers.
        private static void OnChanged(object source, FileSystemEventArgs e)
        {
            
            
            try
            {
                // Create an instance of StreamReader to read from a file.
                // The using statement also closes the StreamReader.
                using (StreamReader sr = new StreamReader("TestFile.txt"))
                {
                    String line;
                    // Read and display lines from the file until the end of 
                    // the file is reached.
                    while ((line = sr.ReadLine()) != null)
                    {
                        Console.WriteLine(line);
                    }
                }
            }
            catch (Exception d)
            {
                // Let the user know what went wrong.
                Console.WriteLine("The file could not be read:");
                Console.WriteLine(d.Message);
            }

        }

     }
}

Recommended Answers

All 7 Replies

e.FullPath gives you the full path of the modified file in private static void OnChanged(object source, FileSystemEventArgs e) . Also since you are using a FileSystemWatcher you know the file is probably in use by another application. In that case you should open the file like this:

//This gives us access to files that are in use by IIS -- sk
      using (FileStream fs = new FileStream(FileName, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
      {
        using (StreamReader sr = new StreamReader(fs))
        {

the filesystem watcher only checks for files being created in that folder, so its not being used by another application.

cheers abotu the e.fullpath thing, how would i actually get/set up the reader to check that directory?

I changed your stream to open e.FullPath . I think you may also want to test that e.FullPath is a file and not a directory.

public static void Run()
    {
      FileSystemWatcher watcher = new FileSystemWatcher();

      watcher.Path = @"C:\text\";//args[1];
      watcher.NotifyFilter = NotifyFilters.LastAccess | NotifyFilters.LastWrite | NotifyFilters.FileName | NotifyFilters.DirectoryName;
      watcher.Filter = "TransferComplete.*";
      watcher.Created += new FileSystemEventHandler(OnChanged);
      watcher.EnableRaisingEvents = true;

      Console.WriteLine("q to exit");
      while (Console.Read() != 'q')
      {
      }
      watcher.EnableRaisingEvents = false;
      watcher.Dispose();
    }

    private static void OnChanged(object source, FileSystemEventArgs e)
    {
      System.Diagnostics.Debugger.Break();
      try
      {
        using (StreamReader sr = new StreamReader(e.FullPath))
        {
          String line;
          while ((line = sr.ReadLine()) != null)
          {
            Console.WriteLine(line);
          }
        }
      }
      catch (Exception d)
      {
        Console.WriteLine("The file could not be read:");
        Console.WriteLine(d.Message);
      }
    }

To get the folder not the file i needed:

Path.GetDirectoryName(e.FullPath)

as you predicted, access to the file was denied, although i dont know why, its not actually in use by another application? and i cant use the code you gave me as i cant specify a filename, as it is eventually going read the lines of each file in the folder ive got it to point to.

how could i get passed that?

Why can't you specify the filename? You are obviously opening a file .. so whether you iterate every file in the directory, open a hard coded file, or anything just change the streams you use to the original streams I posted.

using (StreamReader sr = new StreamReader("TestFile.txt"))

Change that stream line to the two streams I posted earlier if you're using a hard coded file?

I think you need to explain what you are trying to do because this make absolutely no sense so i'm unable to give you better answers.

i am basically monitoring a folder, and there are files being passed into it, but when a file comes in called "TransferComplete" i want it to go through the other files in the folder, taking whats in them and putting them all into 1 different file in another folder,

right now im working on just reading to the console what is in each file. but i am having trouble,

does that clear things up?

private static void OnChanged(object source, FileSystemEventArgs e)
    {
      DirectoryInfo dr = new DirectoryInfo(Path.GetDirectoryName(e.FullPath));
      FileInfo[] files = dr.GetFiles("TransferComplete.*");
      foreach (FileInfo file in files)
      {
        try
        {
          //This gives us access to files that are in use by IIS -- sk
          using (FileStream fs = new FileStream(file.FullName, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
          {
            using (StreamReader sr = new StreamReader(fs))
            {
              string line;
              while ((line = sr.ReadLine()) != null)
              {
                Console.WriteLine(line);
              }
            }
          }
        }
        catch (Exception d)
        {
          Console.WriteLine("The file could not be read:");
          Console.WriteLine(d.Message);
          continue;
        }
      }
    }
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.