简体   繁体   English

c#文件使用.gzip压缩

[英]c# file compress with .gzip

I am trying to compress files with GZIP and my application monitors a folder for new files. 我试图用GZIP压缩文件,我的应用程序监视一个文件夹中的新文件。 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? 任何人都可以帮我解决问题吗?

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. 在您的代码中,您将路径与Path.Combine方法与另一个完全限定的路径组合在一起。

Please see the code below. 请参阅下面的代码。 Another issue could be related to the hard coded path. 另一个问题可能与硬编码路径有关。 Is the file named Input or Input.gz? 该文件名为Input或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);
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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