System.UnauthorizedAccessException,如何访问这些文件?

时间:2017-08-03 07:50:50

标签: c# file model-view-controller io zip

我尝试压缩项目中包含的“export”文件夹中的文件。但是返回了System.UnauthorizedAccessException,它表示拒绝访问。我如何到达导出文件?

   public static void ZipHelper(string path)
    {
        string startPath = path;
        string zipPath = path;
        string extractPath = path;

        ZipFile.CreateFromDirectory(startPath, zipPath);

        ZipFile.ExtractToDirectory(zipPath, extractPath);
    }

我从控制器那里调用了这个函数:

     Helpers.ZipArchiveHelper.ZipHelper(Server.MapPath("~/export "));

这个块是我创建文件的地方。我使用Newtonsoft对数据库表进行了序列化并将它们保存为JSON文件。最后一件事是将这些json文件压缩成一个zip文件。

     name = "componentType.json";
        if (!System.IO.File.Exists(Server.MapPath("~/export") + "\\" + name))
        {
            JsonSerializer serializer = new JsonSerializer();

            var data = JsonConvert.SerializeObject(compTypeList, Formatting.Indented);
            System.IO.File.WriteAllText(Server.MapPath("~/export ") + "\\" + name, data);
        }
        using (StreamReader sr = new StreamReader(Server.MapPath("~/export ") + "\\" + name))
        {
            var jsonObj = new System.Runtime.Serialization.Json.DataContractJsonSerializer(typeof(List<ComponentTypeModel>));
            MemoryStream stream = new MemoryStream(System.Text.Encoding.UTF8.GetBytes(sr.ReadToEnd()));
            compTypeList = (List<ComponentTypeModel>)jsonObj.ReadObject(stream);
        }

我想我需要在上面的部分做一些改动但是找不到。

1 个答案:

答案 0 :(得分:0)

     System.IO.File.SetAttributes(Server.MapPath("~/export"),
                    (new FileInfo(Server.MapPath("~/export"))).Attributes | FileAttributes.Normal);

我在JsonSerializer之前添加了这些行并且它有效。