[英]c# .dat upload file to ftp struggling to find a working example for my console app
好的,所以我想使用c#2010将文件发送到我的drivehq ftp服务器,我已经尝试在控制台应用程序中使用multipul示例,其中一些已上载文件,但始终损坏,其他不起作用,请有人帮助我如何上载a .dat文件到ftp没有损坏,请帮助
文件的原始大小与上载时不同,并且文件已损坏
我的源代码
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Linq;
using System.Text;
using System.Collections.Specialized;
using System.Net;
using System.IO;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
string userName = Environment.UserName;
if (File.Exists(@"C:\Users\" + userName + @"\AppData\Roaming\minefarm\stats.dat"))
{
Console.WriteLine("The file exists.");
// Get the object used to communicate with the server.
FtpWebRequest request = (FtpWebRequest)WebRequest.Create("ftp://ftp.drivehq.com/btc/" + userName + (GetPublicIpAddress() + ".dat"));
request.Method = WebRequestMethods.Ftp.UploadFile;
// This example assumes the FTP site uses anonymous logon.
request.Credentials = new NetworkCredential("user", "pass");
// Copy the contents of the file to the request stream.
StreamReader sourceStream = new StreamReader(@"C:\Users\" + userName + @"\AppData\Roaming\minefarm\stats.dat"));
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();
Console.WriteLine("Upload File Complete, status {0}", response.StatusDescription);
response.Close();
System.Threading.Thread.Sleep(5000);
}
}
private static string GetPublicIpAddress()
{
var request = (HttpWebRequest)WebRequest.Create("http://ifconfig.me");
request.UserAgent = "curl"; // this simulate curl linux command
string publicIPAddress;
request.Method = "GET";
using (WebResponse response = request.GetResponse())
{
using (var reader = new StreamReader(response.GetResponseStream()))
{
publicIPAddress = reader.ReadToEnd();
}
}
return publicIPAddress.Replace("\n", "");
}
}
}
您正在使用System.Net.FtpWebRequest
吗? 您是否适当地设置UseBinary
属性的值?
我怀疑如果您正在传输文件,但显示出了一些损坏,则可能未正确设置UseBinary
。
查看新发布的代码后,即使您正在传输似乎是文本文件的文件,我也没有设置UseBinary = false。 如果服务器的操作系统与客户端的操作系统不同,则通常大小会有所不同,因为Windows用回车符+换行符( "\\r\\n"
)表示行的结尾,而Linux仅使用换行符( "\\n"
)。
为了提供更多有用的信息,我认为您需要找出并详细描述文件的损坏方式。 将文件加载到二进制编辑器中,并查找它们最初的不同之处。
如果您的文件不是文本,则损坏可能是由UTF8.GetBytes引入的,它旨在将数据转换为文本字符。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.