C# - 通过FTP上传文件 [英] C# - Uploading Files through FTP

查看:217
本文介绍了C# - 通过FTP上传文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

大家好!



我正在处理与FTP上传文件有关的项目元素。这是我必须上传所有类型文件的代码。



Hi everyone!

I am working on an element of a project that has to do with FTP uploading files. This is the code that I have to upload all types of files.

#region FTP Upload
// Get the object used to communicate with the server.
FtpWebRequest request = (FtpWebRequest)WebRequest.Create(ftpSite + Path.GetFileName(newFile));
request.Method = WebRequestMethods.Ftp.UploadFile;

request.Credentials = new NetworkCredential(ftpUserNameTextBox.Text.Trim(), ftpPasswordTextBox.Text.Trim());

// Copy the contents of the file to the request stream.
StreamReader sourceStream = null;

sourceStream = new StreamReader("where-file-is-stored" + newFile);

byte[] fileContents = Encoding.UTF8.GetBytes(sourceStream.ReadToEnd());
request.KeepAlive = true;
request.ReadWriteTimeout = 1200000; // 20 minutes
sourceStream.Close();
request.ContentLength = fileContents.Length;

Stream requestStream = request.GetRequestStream();
requestStream.Write(fileContents, 0, fileContents.Length);
requestStream.Close();

FtpWebResponse response = (FtpWebResponse)request.GetResponse();

response.Close();
#endregion





所有类型的如果我在上传后重新下载文件似乎没问题。但是,如果我使用此代码上载后下载.sdf(SQL Server CE)文件,它似乎已损坏。是否有一个我缺少的设置会阻止这些类型的文件被破坏?



非常感谢大家!



All types of files seem to be ok if I re-download them after being uploaded. However, if I download a .sdf (SQL Server CE) file after it is uploaded with this code, it seems to be getting corrupted. Is there a setting that I'm missing that will keep these types of files from getting corrupted?

Thanks so much everyone!

推荐答案

你应该使用BinaryReader而不是流阅读器。您正在将所有字节转换为UTF-8,并且可能会搞乱任何二进制文件,因为它可能检测到不同的编码。使用BinaryReader,您不需要使用Encoding.UTF8.GetBytes,只需使用阅读器上的方法来读取原始字节。
You should use a BinaryReader instead of a stream reader. You are converting all the bytes to UTF-8 and probably screwing up anything that is binary since it is probably detecting a different encoding. With BinaryReader you don't need to use the Encoding.UTF8.GetBytes, just use the methods on the reader to read the raw bytes.


这篇关于C# - 通过FTP上传文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆