-1

I'm trying to create a program where every time i create a text file,it will compress the file and log it . It works for the first text file but when i create the second one, i get this exception: System.Collections.ListDictionaryInternal

Error:The process cannot access the file 'D:\TemeC#\FilesHomework\FilesHomework\ obj\Debug\New Text Document.txt' because it is being used by another process.

This is my code:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.IO;
using System.IO.Compression;
using System.Security.Permissions;

namespace FilesHomework
{
    class Program
    {

        static void Main(string[] args)
        {

            Run();
        }
        [PermissionSet(SecurityAction.Demand, Name = "FullTrust")]
        public static void Run()
        {

            FileSystemWatcher watcher = new FileSystemWatcher();
            watcher.Path = "D:";
            watcher.NotifyFilter = NotifyFilters.LastAccess | NotifyFilters.LastWrite
           | NotifyFilters.FileName | NotifyFilters.DirectoryName;
            watcher.Filter = "*.txt";
            watcher.Created += new FileSystemEventHandler(OnChanged);
            watcher.EnableRaisingEvents = true;
            Console.WriteLine("Press \'q\' to quit the sample.");
            while (Console.Read() != 'q') ;

        }

        private static void OnChanged(object source, FileSystemEventArgs e)
        {
            try {
                FileInfo FileIn = new FileInfo(e.Name);
                Compress(FileIn);
                // FileStream LogFile = File.Open("LogFile.txt",FileMode.OpenOrCreate,FileAccess.ReadWrite,FileShare.ReadWrite);
                //  File.SetAttributes("LogFile.txt", FileAttributes.Normal);
                //  StreamWriter sw = new StreamWriter(LogFile);
                string str;

                str = ("The file " + e.Name + " has been deleted at  " + DateTime.Now);
                // byte[] b1 = System.Text.Encoding.UTF8.GetBytes(str);
                //  sw.WriteLine(str);
                Console.WriteLine(str);
                File.Delete(e.Name);


                //  LogFile.Close();
                //    sw.Close();
            }
            catch(Exception er)
            {
                Console.WriteLine("Error:" + er.Data);
            }


        }
        public static void Compress(FileInfo fileSelected)
        {

            using (FileStream originalFileStream = fileSelected.OpenRead())
            {
                if ((File.GetAttributes(fileSelected.FullName) &
                   FileAttributes.Hidden) != FileAttributes.Hidden & fileSelected.Extension != ".gz")
                {
                    using (FileStream compressedFileStream = File.Create(fileSelected.Name+ ".gz"))
                    {
                        using (GZipStream compressionStream = new GZipStream(compressedFileStream,
                           CompressionMode.Compress))
                        {
                            originalFileStream.CopyTo(compressionStream);


                        }
                    }

                }


            }

        }
    }
}

What do you guys think i should do?

StayOnTarget
  • 11,743
  • 10
  • 52
  • 81
PopaPetru
  • 11
  • 1
  • 2
  • 6
  • 6
    Please post the full stack trace. At the moment *all* we know about the error is `System.Collections.ListDictionaryInternal` which isn't *nearly* enough detail. – Jon Skeet Oct 06 '15 at 08:12
  • 3
    Welcome to Stack Overflow. To be able to help we need more details. What is the exception message? Can you remove some of the code and make a minimal example of the problem? – Anders Abel Oct 06 '15 at 08:12
  • That's the detailed error. Sorry for earlier. Error:The process cannot access the file 'D:\TemeC#\FilesHomework\FilesHomework\ obj\Debug\New Text Document.txt' because it is being used by another process. – PopaPetru Oct 06 '15 at 08:34
  • the error message clearly says a file isn't closed properly. – Amit Kumar Ghosh Oct 06 '15 at 09:42

1 Answers1

1

Ahh, I think I see the problem.

It looks like your code is trying to pick up the new file, before you actually close the file in your editor.

You need to introduce a mechanism into your Compress method that checks if the file is available to open first.

See this answer to check if a file can be accessed or not, in code:

Is there a way to check if a file is in use?

Edit:

I would also try changing the FileSystemWatcher event you use to be .Changed, which fires after a file attribute is changed.

I would still check you can Open it to read by the link above though.

Community
  • 1
  • 1
Russ Clarke
  • 17,511
  • 4
  • 41
  • 45