我正在使用Make目录创建文件夹和我的ftp中的子文件夹(使用filezilla)工作正常,但是当我尝试在我的测试服务器(IIS FTP)中不起作用时,抛出550,找不到文件或没有access.so只是一个快速的方法来更改代码以在我的ftp服务器中创建子目录工作正常,但我知道它有点像这样做。
根据@Markus
更改了我的代码 var dir = new ConsoleApplication5.Program();
string path = "ftp://1.1.1.1/testsvr01/times/" + "testfile" + "/svr01fileName";
string[] pathsplit = path.ToString().Split('/');
string Firstpath = pathsplit[0] + "/" + pathsplit[1] + "/" + pathsplit[2] + "/" + pathsplit[3] + "/";
string SecondPath = Firstpath + "/" + pathsplit[4] + "/";
string ThirdPath = SecondPath + "/" + pathsplit[5] + "/";
string[] paths = { Firstpath, SecondPath, ThirdPath };
foreach (string pat in paths)
{
bool result= dir.EnsureDirectoryExists(pat);
if (result==true)
{
//do nothing
}
else
{ //create dir
dir.createdir(pat);
}
}
upload(path,filename);
}
private bool EnsureDirectoryExists(string pat)
{
try
{
//call the method the first path is exist ?
FtpWebRequest request = (FtpWebRequest)WebRequest.Create(pat);
request.Method = WebRequestMethods.Ftp.ListDirectory;
request.Credentials = new NetworkCredential("sh", "se");
using (FtpWebResponse response = (FtpWebResponse)request.GetResponse())
{
return true;
}
}
catch (Exception ex)
{ return false; }
}
public void createdir(string pat)
{
try
{
FtpWebRequest createdir = (FtpWebRequest)FtpWebRequest.Create(new Uri(pat));
createdir.Method = WebRequestMethods.Ftp.MakeDirectory;
createdir.Credentials = new NetworkCredential("sh", "se");
createdir.UsePassive = true;
createdir.UseBinary = true;
createdir.KeepAlive = false;
FtpWebResponse response1 = (FtpWebResponse)createdir.GetResponse();
Stream ftpStream1 = response1.GetResponseStream();
ftpStream1.Close();
response1.Close();
}
catch (Exception ex)
{
}
}
如果你们中的任何人找到更好的方法,请建议我。
答案 0 :(得分:0)
这是确保目录存在的很多代码。是否有Directory.Exists()方法(或您可以利用的类似方法)?然后你可以在上传之前调用EnsureDirectoryExists()。
private bool EnsureDirectoryExists(string path)
{
// check if it exists
if (Directory.Exists(path))
return true;
string parentPath = GetParentPath(path);
if (parentPath == null)
return false;
bool result = EnsureDirectoryExists(parentPath);
if (result)
{
CreateDirectory(path);
return true;
}
return false;
}
免责声明:您可能需要稍微调整一下逻辑并使用FTP功能,但我希望您明白这一点。