gpt4 book ai didi

c# - 如何在 C# 中将字符串数据作为 ZIP 存档上传到 FTP 服务器

转载 作者:行者123 更新时间:2023-12-04 08:02:45 26 4
gpt4 key购买 nike

这是我的代码。我想导出/上传这个 .dat将文件压缩为 zip 格式到 FTP 服务器。
我尝试了很多,但没有找到任何解决方案。任何人都可以帮助我解决这个问题。

public string ExportVoid(FileSetups fileSetup, HttpPostedFileBase file)
{
var sb = new System.Text.StringBuilder();

var list = _context.VOIDS.ToList();

foreach (var item in list)
{
sb.AppendFormat("{0}\t{1}\t{2}\t{3}\t{4}\t{5}\t{6}\t{7}\t{8}\r", item.Date, item.Time, item.Shift, item.EmployeeID, item.Amount, item.Items, item.DrawerOpen, item.Postpone, item.LocationID);
}
System.Web.HttpResponse response = System.Web.HttpContext.Current.Response;

WebClient myWebClient = new WebClient();
var dbftp = _context.FileSetup.SingleOrDefault();
var a = dbftp.FTP;
var v = Session["ClientId"];
var d = DateTime.Now.ToString("MM_dd_yyyy_hh:mm:ss");
string uriString = "ftp://MyFTP.com/Files/" + "Void" + ".dat";
myWebClient.Credentials = new NetworkCredential("userName", "password");
//Console.WriteLine("\nPlease enter the data to be posted to the URI {0}:", uriString);
string postData = sb.ToString();
// Apply ASCII Encoding to obtain the string as a byte array.
byte[] postArray = Encoding.ASCII.GetBytes(postData);

myWebClient.Headers.Add("Content-Disposition", "attachment; filename=" + "Void.dat");

byte[] responseArray = myWebClient.UploadData(uriString, postArray);

return "Export Successfully!";
}

最佳答案

如果要压缩内存中的字符串 ( postData ) 并将压缩文件上传到 FTP 服务器,可以使用:

using (var memoryStream = new MemoryStream())
{
using (var archive = new ZipArchive(memoryStream, ZipArchiveMode.Create, true))
{
// Repeat this block, if you want to add more files
ZipArchiveEntry entry = archive.CreateEntry("void.dat");

using (Stream entryStream = entry.Open())
using (var writer = new StreamWriter(entryStream, Encoding.UTF8))
{
writer.Write(postData);
}
}

memoryStream.Seek(0, SeekOrigin.Begin);

var request = WebRequest.Create("ftp://ftp.example.com/remote/path/archive.zip");
request.Credentials = new NetworkCredential("username", "password");
request.Method = WebRequestMethods.Ftp.UploadFile;
using (Stream ftpStream = request.GetRequestStream())
{
memoryStream.CopyTo(ftpStream);
}
}
如果文本很小,以至于内存占用无关紧要,则可以将上传代码(从 memoryStream.Seek 到末尾的所有内容)简化为:
    var client = new WebClient();
client.Credentials = new NetworkCredential("username", "password");
client.UploadData(
"ftp://ftp.example.com/remote/path/archive.zip", memoryStream.ToArray());

基于 Zip a directory and upload to FTP server without saving the .zip file locally in C# .

您关于相反操作的相关问题:
How to import data from a ZIP file stored on FTP server to database in C#

关于c# - 如何在 C# 中将字符串数据作为 ZIP 存档上传到 FTP 服务器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66366766/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com