这是我的代码:
public static string DownloadFile(string FtpUrl, string FileNameToDownload,
string userName, string password, string tempDirPath)
{
string ResponseDescription = "";
string PureFileName = new FileInfo(FileNameToDownload).Name;
string DownloadedFilePath = tempDirPath + "/" + PureFileName;
string downloadUrl = String.Format("{0}/{1}", FtpUrl, FileNameToDownload);
FtpWebRequest req = (FtpWebRequest)FtpWebRequest.Create(downloadUrl);
req.Method = WebRequestMethods.Ftp.DownloadFile;
req.Credentials = new NetworkCredential(userName, password);
req.UseBinary = true;
req.Proxy = null;
try
{
FtpWebResponse response = (FtpWebResponse)req.GetResponse();
Stream stream = response.GetResponseStream();
byte[] buffer = new byte[2048];
FileStream fs = new FileStream(DownloadedFilePath, FileMode.Create);
int ReadCount = stream.Read(buffer, 0, buffer.Length);
while (ReadCount > 0)
{
fs.Write(buffer, 0, ReadCount);
ReadCount = stream.Read(buffer, 0, buffer.Length);
}
ResponseDescription = response.StatusDescription;
fs.Close();
stream.Close();
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
return ResponseDescription;
}
}
此代码从 ftp 服务器下载文件并将其写入服务器中的特定路径。
但保存的文件的编码不是UTF-8。
我想将文件的编码类型更改为UTF-8。
我必须使用 StreamReader 吗?
我怎样才能修改该代码?
理论上,以下内容应该有效,但这取决于响应流是否可以与流读取器一起工作。
使用不同的编码进行写入很容易,您可以简单地使用流写入器(基于文本写入器)而不是文件流。但是,您不能直接写入字节,因为您必须写入格式正确的文本。为此,必须使用正确的原始编码将字节转换为文本(字符缓冲区)。
char[] buffer = new char[2048]; //or 1024 if you want to keep the same block size
using (var reader = new StreamReader(stream, Encoding.Unicode)) // <= Or whatever encoding the orignal is
{
using (var tw = new StreamWriter(DownloadedFilePath, false, Encoding.UTF8)) //streamwriter instead of filestream
{
while (true)
{
int ReadCount = reader.Read(buffer, 0, buffer.Length);
if (ReadCount == 0) break;
tw.Write(buffer, 0, ReadCount);
}
ResponseDescription = response.StatusDescription;
stream.Close();
tw.Close();
}
}
如果流读取器出现问题,您还可以先下载字节,然后对已下载的字节使用流读取器。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)