【发布时间】:2015-01-06 00:41:19
【问题描述】:
这是一个将文本文件上传到我的 ftp 根目录的工作代码。测试和工作。 但是现在我想在根目录上创建一个子目录,然后在创建目录后上传文件。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
using System.Net;
namespace mws
{
class FtpFileUpload
{
static string ftpurl = "ftp://ftp.newsxpressmedia.com/";
static string filename = @"c:\temp\FtpTestFile.txt";
static string ftpusername = "Username";
static string ftppassword = "Password";
static string ftpdirectory = "subtestdir";
public static void test()
{
try
{
FtpWebRequest request = (FtpWebRequest)FtpWebRequest.Create(
ftpurl + "/" + Path.GetFileName(filename));
request.Method = WebRequestMethods.Ftp.UploadFile;
request.Credentials = new NetworkCredential(ftpusername, ftppassword);
StreamReader sourceStream = new StreamReader(@"c:\temp\test1.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();
}
catch (Exception err)
{
string t = err.ToString();
}
}
}
}
我尝试更改第一行并添加了一行来创建目录:
FtpWebRequest request = (FtpWebRequest)FtpWebRequest.Create(
ftpurl + "/" + ftpdirectory + "/" + Path.GetFileName(filename));
request.Method = WebRequestMethods.Ftp.MakeDirectory;
然后我收到异常错误:
远程服务器返回错误:(550) 文件不可用(例如,找不到文件,无法访问)。
但在更改之前它工作正常没有问题。 如何先在我的服务器上创建一个目录,然后将文件上传到创建的目录?
【问题讨论】: