如何删除文件名创建ZIP文件时的GUID? [英] How to remove guid from file name when creating zip file?
问题描述
当用户上传多个文档,我自己存储的文件在我的项目是这样的:
When user uploads multiple documents I am storing their files in my project like this:
Guid id;
id = Guid.NewGuid();
string filePath = Path.Combine(HttpContext.Server.MapPath("../Uploads"),
Path.GetFileName(id + item.FileName));
item.SaveAs(filePath);
所以文件都在我的项目保存这样的:
So files are saved like this in my project:
- 1250a2d5-cd40-4bcc-a979-9d6f2cd62b9fLog.txt
- bdb31966-e3c4-4344-B02C-305c0eb0fa0aLogging.txt
现在创建压缩文件时,我收到此文件同名的压缩zip文件的时候,但我不经过用户下载的文件我的文件名希望GUID。
Now when creating zip files I am getting same name of this files when extracting zip files but I don't want guid in my file name after user downloads file.
不过,我曾试图remove从我的文件名的GUID,但得到的错误 System.IO.FileNotFoundException
。
However I have tried to remove guid from my file name but getting error System.IO.FileNotFoundException
.
这是我的code:
using (var zip = new ZipFile())
{
var str = new string[] { "1250a2d5-cd40-4bcc-a979-9d6f2cd62b9fLog.txt", "bdb31966-e3c4-4344-b02c-305c0eb0fa0aLogging.txt" }; //file name are Log.txt and Logging.txt
string[] str1 = str .Split(',');
foreach (var item in str1)
{
string filePath = Server.MapPath("~/Uploads/" + item.Substring(36));//as guid are of 36 digits
zip.AddFile(filePath, "files");
}
zip.Save(memoryStream);//Getting error here
}
任何人可以帮助我呢?
Can anybody help me with this?
推荐答案
ZipFile中抛出一个异常,因为它无法找到磁盘上的文件,因为你给了它一个不存在的文件的名称(通过执行.Substring())。为了使它工作,你就必须使用File.Copy文件与新的文件名重命名,然后给出相同的文件名Zip.AddFile()。
ZipFile is throwing an exception because it can't find the file on disk as you have given it a name of a file that does not exist (by doing a .Substring()). To make it work you would have to rename the file using File.Copy with your new file name and then give that same file name to Zip.AddFile().
var orgFileName = "1250a2d5-cd40-4bcc-a979-9d6f2cd62b9fLog.txt";
var newFileName = orgFileName.Substring (36);
File.Copy (orgFileName, newFileName, true);
zip.AddFile (newFileName);
这篇关于如何删除文件名创建ZIP文件时的GUID?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!