This is a working code that upload text file to my ftp root. Tested and working. But now i want to create a sub directory on the root directory and then after creating the directory to upload the file.
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();
}
}
}
}
I tried to change the first line and added also a line to create a directory:
FtpWebRequest request = (FtpWebRequest)FtpWebRequest.Create(
ftpurl + "/" + ftpdirectory + "/" + Path.GetFileName(filename));
request.Method = WebRequestMethods.Ftp.MakeDirectory;
But then i'm getting exception error:
The remote server returned an error: (550) File unavailable (e.g., file not found, no access).
But before the changes it's working fine no problems. How can i create a directory on my server first and then upload the file to the created directory ?