我已经尝试过这个代码将文件上传到ftp服务器但是出现了这个错误。我不会在哪里出错。 我尝试了各种方法来改变我的ftpurl格式,但仍然没有运气。
代码:
private void button1_Click_1(object sender, EventArgs e)
{
UploadFileToFTP(sourcefilepath);
}
private static void UploadFileToFTP(string source)
{
String sourcefilepath = "C:/Users/Desktop/LUVS/*.xml";
String ftpurl = "100.100.0.35"; // e.g. fake IDs
String ftpusername = "ftp"; // e.g. fake username
String ftppassword = "1now"; // e.g. fake password
try
{
string filename = Path.GetFileName(source);
string ftpfullpath = ftpurl;
FtpWebRequest ftp = (FtpWebRequest)FtpWebRequest.Create(ftpfullpath);
ftp.Credentials = new NetworkCredential(ftpusername, ftppassword);
ftp.KeepAlive = true;
ftp.UseBinary = true;
ftp.Method = WebRequestMethods.Ftp.UploadFile;
FileStream fs = File.OpenRead(source);
byte[] buffer = new byte[fs.Length];
fs.Read(buffer, 0, buffer.Length);
fs.Close();
Stream ftpstream = ftp.GetRequestStream();
ftpstream.Write(buffer, 0, buffer.Length);
ftpstream.Close();
}
catch (Exception ex)
{
throw ex;
}
答案 0 :(得分:3)
错误在ftp网址中。您尚未包含文件名。写得像这样:
private static void UploadFileToFTP(string source)
{
String sourcefilepath = "C:\\Users\\Desktop\\LUVS\\a.xml";
String ftpurl = "100.100.0.35"; // e.g. fake IDs
String ftpusername = "ftp"; // e.g. fake username
String ftppassword = "1now"; // e.g. fake password
try
{
string filename = Path.GetFileName(sourcefilepath);
string ftpfullpath = "ftp://" + ftpurl + "/" + filename ;
FtpWebRequest ftp = (FtpWebRequest)FtpWebRequest.Create(ftpfullpath);
ftp.Credentials = new NetworkCredential(ftpusername, ftppassword);
ftp.KeepAlive = true;
ftp.UseBinary = true;
ftp.Method = WebRequestMethods.Ftp.UploadFile;
FileStream fs = File.OpenRead(sourcefilepath); // here, use sourcefilepath insted of source.
byte[] buffer = new byte[fs.Length];
fs.Read(buffer, 0, buffer.Length);
fs.Close();
Stream ftpstream = ftp.GetRequestStream();
ftpstream.Write(buffer, 0, buffer.Length);
ftpstream.Close();
}
catch (Exception ex)
{
throw ex;
}
}
答案 1 :(得分:2)
Create
方法似乎位于WebRequest
上,而不是FtpWebRequest
上。并且WebRequest
需要根据URI的格式从URI 确定要创建的子对象(在本例中为FtpWebRequest
)。但是你的URI只是一个简单的地址:
"100.100.0.35"
如果您预先添加协议,它应该能够从URI确定它需要什么:
"ftp://100.100.0.35"