1

I am trying to compress files with GZIP and my application monitors a folder for new files. When a new file comes in, it should be compressed and then application should continue doing this every time a new file comes in folder.

private void Compress(string filePath)
    {

      using (FileStream inputStream = new FileStream(filePath,FileMode.OpenOrCreate,FileAccess.ReadWrite))
        {
            using (FileStream outputStream = new FileStream(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), @"C:\\Users\\maki\\Desktop\\Input"), FileMode.OpenOrCreate, FileAccess.ReadWrite))//'System.UnauthorizedAccessException' 
            {
                using (GZipStream gzip = new GZipStream(outputStream, CompressionMode.Compress))
                {
                    inputStream.CopyTo(gzip);
                }
            }
        }


    }

when I execute the application, I get this exception:

An unhandled exception of type 'System.UnauthorizedAccessException' occurred in mscorlib.dll

Additional information:

Access to the path 'C:\Users\maki\Desktop\Input' is denied.

I've searched a lot in internet but couldn't find a proper answer.

Can anyone help me with issue?

Youn Elan
  • 2,379
  • 3
  • 23
  • 32
maki
  • 37
  • 1
  • 1
  • 8
  • 1
    Given that the error is occurring before you do anything with gzip, it seems unlikely that it's *related* to gzip. Basically, this is a matter of not being able to write to a particular path... and I suspect that's because the way you're constructing the path is broken. – Jon Skeet Jan 10 '17 at 19:49
  • I think I would assign that Path.Combine statement to a string value, then inspect that in the debugger to make sure you are working with a valid path. – David Green Jan 10 '17 at 21:05

1 Answers1

2

The issue could be related you to the way the file stream is instantiated. In your code, you are combining a path, with the Path.Combine method with another fully qualified path.

Please see the code below. Another issue could be related to the hard coded path. Is the file named Input or Input.gz? Also note the ability to stack using statements for reduced nesting.

private void Compress(string filePath)
{
    using (FileStream inputStream = 
        new FileStream(filePath, FileMode.OpenOrCreate, FileAccess.ReadWrite))
    using (FileStream outputStream =
        new FileStream(@"C:\\Users\\maki\\Desktop\\Input",
            FileMode.OpenOrCreate, FileAccess.ReadWrite)) 
    using (GZipStream gzip = new GZipStream(outputStream, CompressionMode.Compress))
    {
        inputStream.CopyTo(gzip);
    }
}
Paul Tsai
  • 893
  • 6
  • 16