指点成金-最美分享吧

登录

c# 移动单个文件到文件夹中

佚名 举报

篇首语:本文由小编为大家整理,主要介绍了c# 移动单个文件到文件夹中相关的知识,希望对你有一定的参考价值。

如何使用c#,将一个文件(1.jpg)复制到一个文件夹中(不是复制整个文件夹到新的文件夹!!!!!是把文件复制到文件夹)求大神帮忙~~~

  使用File.Move 方法,通过代码File.Move("要移动的文件路径",“目标文件夹\\文件名"),就可以移动单个文件到文件夹。

File.Move 方法说明:
  File.Move 方法
  将指定文件移到新位置,并提供指定新文件名的选项。
Namespace: System.IO
程序集: mscorlib(位于 mscorlib.dll 中)
  语法
public static void Move(
string sourceFileName,
string destFileName
)
  参数
sourceFileName
类型: System.String
要移动的文件的名称。
destFileName
类型: System.String
文件的新路径。
参考技术A  var sourceFilePath = "c:/dir/1.jpg";
 var file = new FileInfo(sourceFilePath);
 var destFileName = "目标文件夹/" + file.Name;
 File.Copy(sourceFilePath, destFileName);

本回答被提问者采纳
参考技术B var sourceFilePath = "c:/dir/1.jpg";
var file = new FileInfo(sourceFilePath);
var destFileName = "目标文件夹/" + file.Name;
File.Copy(sourceFilePath, destFileName);
参考技术C File.Move("1.jpg",文件夹路劲+“1.jpg”); 参考技术D File.Move()

使用 C# 将单个文件添加到大型 ZIP 文件的快速方法

【中文标题】使用 C# 将单个文件添加到大型 ZIP 文件的快速方法【英文标题】:Fast way to add a single file to a large ZIP file using C# 【发布时间】:2018-08-28 11:38:42 【问题描述】:

我有一个大的 zip 文件(比如 10 GB),我想在其中添加一个小文件(比如 50 KB)。我正在使用以下代码:

using System.IO.Compression;using (var targetZip = ZipFile.Open(largeZipFilePath), ZipArchiveMode.Update)    targetZip.CreateEntryFromFile(smallFilePath, "foobar");

虽然这有效(最终),但它需要很长时间并消耗大量内存。它似乎提取并重新压缩了整个存档。

如何在 .Net 4.7 中改进这一点?没有外部依赖的解决方案是首选,但如果不可能,则不需要。

【问题讨论】:

【参考方案1】:

使用 Visual Studio nuget 包管理器并安装它

安装包 DotNetZip -Version 1.11.0

    using (ZipFile zip = new ZipFile())      zip.AddFile("ReadMe.txt"); // no password for this one    zip.Password= "123456!";    zip.AddFile("7440-N49th.jpg");    zip.Password= "!Secret1";    zip.AddFile("2005_Annual_Report.pdf");    zip.Save("Backup.zip");  

https://www.nuget.org/packages/DotNetZip/

【讨论】:

【参考方案2】:

由于您处于 .NET 4.5 以上,您可以使用 ZipArchive (System.IO.Compression) 类来实现这一点。这是 MSDN 文档:(MSDN)。

这是他们的示例,它只写入文本,但您可以读取 .csv 文件并将其写入新文件。要仅复制文件,您可以使用 CreateFileFromEntry,它是 ZipArchive 的扩展方法。

using (FileStream zipToOpen = new FileStream(@"c:usersexampleuser
elease.zip", FileMode.Open))   using (ZipArchive archive = new ZipArchive(zipToOpen, ZipArchiveMode.Update))          ZipArchiveEntry readmeEntry = archive.CreateEntry("Readme.txt");       using (StreamWriter writer = new StreamWriter(readmeEntry.Open()))                  writer.WriteLine("Information about this package.");           writer.WriteLine("========================");          

检查这个:- https://***.com/a/22339337/9912441

https://docs.microsoft.com/en-us/dotnet/standard/io/how-to-compress-and-extract-files

【讨论】:

ZipArchive.CreateEntryFromFile() 是我目前正在使用的。在 10 GB zip 存档上使用此代码大约需要 5 分钟和 10 GB 内存,这正是我想要避免的。【参考方案3】:

我在另一个 Stack Overflow 答案中找到了这种行为的原因:Out of memory exception while updating zip in c#.net。

它的要点是这需要很长时间,因为ZipArchiveMode.Update 将 zip 文件缓存到内存中。避免这种缓存行为的建议是创建一个新存档,并将旧存档内容与新文件一起复制到其中。

参见the MSDN documentation,它解释了ZipArchiveMode.Update 的行为方式:

【讨论】:

以上是关于c# 移动单个文件到文件夹中的主要内容,如果未能解决你的问题,请参考以下文章