如何写入远程文件?

时间:2011-06-09 10:44:42

标签: c# file-io remote-access

我需要能够写入位于我的vps上的远程文本文件。我知道如何使用WebRequest,WebResponse读取文件。这可能非常简单。

3 个答案:

答案 0 :(得分:2)

How to: Upload Files with FTP

using System;
using System.IO;
using System.Net;
using System.Text;

namespace Examples.System.Net
{
    public class WebRequestGetExample
    {
        public static void Main ()
        {
            // Get the object used to communicate with the server.
            FtpWebRequest request = (FtpWebRequest)WebRequest.Create("ftp://www.contoso.com/test.htm");
            request.Method = WebRequestMethods.Ftp.UploadFile;

            // This example assumes the FTP site uses anonymous logon.
            request.Credentials = new NetworkCredential ("anonymous","janeDoe@contoso.com");

            // Copy the contents of the file to the request stream.
            StreamReader sourceStream = new StreamReader("testfile.txt");
            byte [] fileContents = Encoding.UTF8.GetBytes(sourceStream.ReadToEnd());
            sourceStream.Close();
            request.ContentLength = fileContents.Length;

            Stream requestStream = request.GetRequestStream();
            requestStream.Write(fileContents, 0, fileContents.Length);
            requestStream.Close();

            FtpWebResponse response = (FtpWebResponse)request.GetResponse();

            Console.WriteLine("Upload File Complete, status {0}", response.StatusDescription);

            response.Close();
        }
    }
}

答案 1 :(得分:0)

由于它是VPS(远程机器),因此没有直接的API或方法。通过telnet或FTP服务器方式。

答案 2 :(得分:0)

您可能需要查看msdn的FtpWebRequest文档,其中包含有关通过ftp上传,下载和删除文件的示例。

还有带文件附件的HttpRequests(例如许多头像上传表单使用的内容)。