我尝试上传图片&视频文件,但使用此代码我的所有图像&视频文件已损坏,如何解码图像和文件?视频?
public void UploadFile(string SouPath, string DestPath, string Login, string Password)
{
try
{
FtpWebRequest request = (FtpWebRequest)FtpWebRequest.Create(DestPath);
request.Credentials = new NetworkCredential(Login, Password);
request.Method = WebRequestMethods.Ftp.UploadFile;
StreamReader sourceStream = new StreamReader(SouPath);
byte[] fileContents = Encoding.UTF8.GetBytes(sourceStream.ReadToEnd()); // **
sourceStream.Close();
request.ContentLength = fileContents.Length;
Stream requestStream = request.GetRequestStream();
requestStream.Write(fileContents, 0, fileContents.Length);
requestStream.Close();
FtpWebResponse response = (FtpWebResponse)request.GetResponse();
String FileName = Path.GetFileName(SouPath);
WriteStoneList("Upload File " + FileName + ". | Status : " + response.StatusDescription);
response.Close();
}
catch (Exception ex)
{
WriteStoneList("`````````````````````````````````````");
WriteStoneList(ex.ToString());
}
}
我试图解码图像,但它无法正常工作。并且我在解码后也得到了损坏的图像。
public static Stream Decode(string Path)
{
String text;
using (StreamReader sr = new StreamReader(Path))
{
text = sr.ReadToEnd();
char[] cc = text.ToArray<char>();
//byte[] bytes = Convert.FromBase64String(text);
//byte[] bytes = Convert.FromBase64CharArray(cc,0,cc.Length);
byte[] bytes = System.IO.File.ReadAllBytes(Path);
System.Text.UTF8Encoding encoder = new System.Text.UTF8Encoding();
System.Text.Decoder decoder = encoder.GetDecoder();
int count = decoder.GetCharCount(bytes, 0, bytes.Length);
char[] arr = new char[count];
decoder.GetChars(bytes, 0, bytes.Length, arr, 0);
text = new string(arr);
MemoryStream stream = new MemoryStream();
StreamWriter writer = new StreamWriter(stream);
writer.Write(text);
writer.Flush();
stream.Position = 0;
return stream;
}
}
我使用了上面的解码功能来获取解码流
public void ConvertFile(string fromPath,string toPath)
{
using (Stream source = Decode(fromPath))
using (Stream dest = File.Create(toPath))
{
byte[] buffer = new byte[1024];
int bytes;
while ((bytes = source.Read(buffer, 0, buffer.Length)) > 0)
{
dest.Write(buffer, 0, bytes);
}
}
}
答案 0 :(得分:2)
StreamReader
会读取文字信息流,当然您的图片会在目的地内损坏。
您过于复杂,WebClient
已经有一个开箱即用的UploadFile
方法:
using (WebClient client = new WebClient())
{
client.Credentials = new NetworkCredential(Login, Password);
client.UploadFile(DestPath, "STOR", SouPath);
}
答案 1 :(得分:0)
图像和视频文件是二进制数据。将它们编码为utf-8将始终损坏此数据。没有必要对这些数据进行编码,只需将数据复制到流中,如下所示:
using(var fin = new FileStream(SouPath))
{
request = fin.Length;
Stream requestStream = request.GetRequestStream();
fin.CopyTo(requestStream);
requestStream.Close();
}
未经过测试