1

我的问题是,当我在我的 ftp 服务器上查看上传的文件时,上面没有内容,它是空的。为什么会发生这种情况,我的代码中缺少某些内容?

if (File.Exists("main.xml"))
{
    using (Stream stream = new MemoryStream())
    {
        stream.Position = 0;
        stream.Seek(0, SeekOrigin.Begin);

        string uri = String.Format("ftp://{0}/{1}/{2}", "host", "wwwroot", "main.xml");

        FtpWebRequest request = (FtpWebRequest)FtpWebRequest.Create(new Uri(uri));

        request.Credentials = new NetworkCredential("user", "pass");
        request.Method = WebRequestMethods.Ftp.UploadFile;
        request.KeepAlive = false;
        request.UseBinary = true;
        request.UsePassive = true;
        request.ContentLength = stream.Length;
        request.EnableSsl = false;

        int bufferLength = 2048;
        byte[] buffer = new byte[bufferLength];
        int contentLength;

        Stream ftpStream = request.GetRequestStream();
        contentLength = stream.Read(buffer, 0, bufferLength);
        while (contentLength != 0)
        {
            ftpStream.Write(buffer, 0, contentLength);
            contentLength = stream.Read(buffer, 0, bufferLength);
        }

        ftpStream.Flush();
        ftpStream.Close();
    }
}
else
{
    MessageBox.Show("No file found.");
}

但是当我尝试在上面插入这行代码时

MessageBox.Show(XDocument.Load("main.xml").ToString());

它有一个输出,

但是当我尝试设置断点时,当它到达while (contentLength != 0)它时不会进入它

4

2 回答 2

1

如果您正在编写的文件总是空的,那么听起来您实际上并没有得到任何文件。首先要检查的是看是否while (contentLength != 0)曾经输入过。

更新:另外,正如约翰指出的那样,请求流分配很糟糕!

于 2013-02-11T03:18:09.663 回答
1

编辑

好的,这应该是

using (Stream stream = File.Open("main.xml", FileMode.Open))
于 2013-02-11T03:18:11.380 回答