我正尝试在ftp服务器上将一个多行文本框流式传输到一个文本文件中。谁能告诉我我可能错在哪里?
private void btnSave_Click(object sender, EventArgs e)
{
UriBuilder b = new UriBuilder();
b.Host = "ftp.myserver.com";
b.UserName = "user";
b.Password = "pass";
b.Port = 21;
b.Path = "/myserver.com/directories/" + selected + ".txt";
b.Scheme = Uri.UriSchemeFtp;
Uri g = b.Uri;
System.Net.FtpWebRequest c = (System.Net.FtpWebRequest)System.Net.FtpWebRequest.Create(g);
c.Method = System.Net.WebRequestMethods.Ftp.DownloadFile;
System.Net.FtpWebResponse d = (System.Net.FtpWebResponse)c.GetResponse();
System.IO.Stream h = d.GetResponseStream;
System.IO.StreamWriter SW = new System.IO.StreamWriter(h);
String[] contents = textBox1.Lines.ToArray();
for (int i = 0; i < contents.Length; i++)
{
SW.WriteLine(contents[i]);
}
h.Close();
SW.Close();
d.Close();
}我得到的错误是下面这行:
新的SW = System.IO.StreamWriter System.IO.StreamWriter(h);
流不可写。
有什么想法吗?
发布于 2010-01-22 21:09:31
来自FTP站点的响应流是从该站点发送给您的数据。你需要请求流...但是你不会想要一个DownloadFile方法--你不是在下载,而是在上传,所以你想要UploadFile方法。
此外:
using块。发布于 2010-01-22 21:11:26
要上传文件,您需要使用FtpWebRequest类。
引用:
使用FtpWebRequest对象将文件上载到服务器时,必须将文件内容写入通过调用
GetRequestStream方法或其异步对应方法BeginGetRequestStream和EndGetRequestStream方法获得的请求流中。在发送请求之前,必须写入流并关闭流。
有关上传文件的示例(您可以将其更改为编写流内容,如示例中所示),请使用see here。
发布于 2010-01-22 21:13:38
取自MSDN,稍作修改:
public static bool UploadFileOnServer(string fileName, Uri serverUri)
{
// The URI described by serverUri should use the ftp:// scheme.
// It contains the name of the file on the server.
// Example: ftp://contoso.com/someFile.txt.
// The fileName parameter identifies the file
// to be uploaded to the server.
if (serverUri.Scheme != Uri.UriSchemeFtp)
{
return false;
}
// Get the object used to communicate with the server.
FtpWebRequest request = (FtpWebRequest)WebRequest.Create(serverUri);
request.Method = WebRequestMethods.Ftp.UploadFile;
StreamReader sourceStream = new StreamReader(fileName);
byte [] fileContents = Encoding.UTF8.GetBytes(sourceStream.ReadToEnd());
sourceStream.Close();
request.ContentLength = fileContents.Length;
// This example assumes the FTP site uses anonymous logon.
request.Credentials = new NetworkCredential ("anonymous","janeDoe@contoso.com");
Stream requestStream = request.GetRequestStream();
requestStream.Write(fileContents, 0, fileContents.Length);
requestStream.Close();
FtpWebResponse response = (FtpWebResponse) request.GetResponse();
Console.WriteLine("Upload status: {0}",response.StatusDescription);
response.Close();
return true;
}https://stackoverflow.com/questions/2117328
复制相似问题