繁体   English   中英

尝试上传(ftp)时C#用空文件覆盖文件

[英]C# overwrite file with empty file when trying to upload (ftp)

我正在尝试通过ftp上传文本文件,当我运行程序时,它将清空我的文件,然后上传它。 我不知道为什么...可能会覆盖它或其他内容...这是我的代码:

这是在主班

        /* Create Object Instance */
        ftp ftpClient = new ftp(@"ftp://sportcaffe.me", "sport***", "*****");

        /* Upload a File */
        ftpClient.upload("public_html/test.txt", @"C:\Users\Lazar\Desktop\test.txt");

这是ftp类功能代码:

/* Upload File */
    public void upload(string remoteFile, string localFile)
    {
        try
        {
            /* Create an FTP Request */
            ftpRequest = (FtpWebRequest)FtpWebRequest.Create(host + "/" + remoteFile);
            /* Log in to the FTP Server with the User Name and Password Provided */
            ftpRequest.Credentials = new NetworkCredential(user, pass);
            /* When in doubt, use these options */
            ftpRequest.UseBinary = true;
            ftpRequest.UsePassive = true;
            ftpRequest.KeepAlive = true;
            /* Specify the Type of FTP Request */
            ftpRequest.Method = WebRequestMethods.Ftp.UploadFile;
            /* Establish Return Communication with the FTP Server */
            ftpStream = ftpRequest.GetRequestStream();
            /* Open a File Stream to Read the File for Upload */
            FileStream localFileStream = new FileStream(localFile, FileMode.Create);
            /* Buffer for the Downloaded Data */
            byte[] byteBuffer = new byte[bufferSize];
            int bytesSent = localFileStream.Read(byteBuffer, 0, bufferSize);
            /* Upload the File by Sending the Buffered Data Until the Transfer is Complete */
            try
            {
                while (bytesSent != 0)
                {
                    ftpStream.Write(byteBuffer, 0, bytesSent);
                    bytesSent = localFileStream.Read(byteBuffer, 0, bufferSize);
                }
            }
            catch (Exception ex) { MessageBox.Show(ex.ToString()); }
            /* Resource Cleanup */
            localFileStream.Close();
            ftpStream.Close();
            ftpRequest = null;
        }
        catch (Exception ex) { MessageBox.Show(ex.ToString()); }
        return;
    }

没有错误和警告...

首先,我在文件中写入一些内容并保存,然后在运行程序时,我的文件为空,并且该empy文件已上传...

我使用此代码http://www.codeproject.com/Tips/443588/Simple-Csharp-FTP-Class

FileStream localFileStream = new FileStream(localFile, FileMode.Create);

我希望我不需要太清楚地拼写出来,但是上面的行被告知要创建一个文件。 引用文档:“指定操作系统应该创建一个新文件。如果该文件已经存在,它将被覆盖。”

http://msdn.microsoft.com/zh-cn/library/system.io.filemode(v=vs.110).aspx列出了您可以在此处使用的选项列表。 FileMode.Open应该可以满足您的需要(它将打开文件,如果文件不存在,则抛出异常)。

解决了

FileStream localFileStream =新的FileStream(localFile,FileMode.Create); 用FileMode.Open替换FileMode.Create

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM