无效的URI:使用文件上传到ftp无法确定URI的格式

时间:2014-06-13 09:48:16

标签: c# ftp

我已经尝试过这个代码将文件上传到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;
            }

2 个答案:

答案 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"