我有一个MVC C#网络服务,我需要将一个字符串转换为具有特定名称的zip文件并返回。
我从各种StackOverFlow帖子中汇编了此代码,但是某些关键字(ZipFile,CreateEntryFromFile)无法识别,而其他关键字(ZipArchive)可以识别
string xmlReply = "This is a test";
//Convert to bytes and encode to Base64
Byte[] bytes = File.ReadAllBytes(xmlReply);
//Write it back to string
xmlReply = Convert.ToBase64String(bytes);
//Write string to file
string filename = @"C:\Users\Public\tr_file";
System.IO.File.WriteAllText(filename, xmlReply);
string fileNameZip = @"C:\Users\Public\FileR.zip";
//Zip
using (ZipArchive zip = ZipFile.Open(fileNameZip, ZipArchiveMode.Create))
{
zip.CreateEntryFromFile(filename, Path.GetFileName(filename));
}
//Break zip into bytes and return it
byte[] fileBytes = System.IO.File.ReadAllBytes(fileNameZip);
return new FileContentResult(fileBytes, "application/zip");
您能帮助指出错误或提出其他实现方法吗?
感谢
编辑:对于缺少的关键字,我发现我需要添加对System.IO.Compression.FileSystem的引用
FileContentResult
会欺骗并退回拉链吗?
答案 0 :(得分:0)
您的代码几乎与this page上的示例十分相似
using System;
using System.IO;
using System.IO.Compression;
namespace ConsoleApplication
{
class Program
{
static void Main(string[] args)
{
string zipPath = @"c:\users\exampleuser\start.zip";
string extractPath = @"c:\users\exampleuser\extract";
string newFile = @"c:\users\exampleuser\NewFile.txt";
using (ZipArchive archive = ZipFile.Open(zipPath, ZipArchiveMode.Update))
{
archive.CreateEntryFromFile(newFile, "NewEntry.txt");
archive.ExtractToDirectory(extractPath);
}
}
}
}
答案 1 :(得分:0)
添加:
using System.IO.Compression;
如果它不起作用,请检查目标框架是否至少为4.5.2