无效的URI:使用文件上传到ftp时无法确定URI的格式
本文关键字:URI ftp 格式 无法确定 文件 无效 | 更新日期: 2023-09-27 18:08:23
我已经尝试了这个代码上传文件到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;
}
错误在ftp url中。您没有包含文件名。这样写:
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;
}
}
Create
方法似乎在WebRequest
上,而不是在FtpWebRequest
上。WebRequest
需要根据URI的格式从URI 确定要创建哪个子对象(在本例中为FtpWebRequest
)。但是你的URI只是一个简单的地址:
"100.100.0.35"
如果您添加了一个协议,它应该能够从URI中确定它需要什么:
"ftp://100.100.0.35"