From Windows OS C# To Linux FTP

patrick

Well-known member
Joined
Dec 5, 2021
Messages
305
Programming Experience
1-3
Hello

From Windows OS C# To Linux FTP ( WindowsOS C# ---Upload--> Linux FTP )

Question-1) Destination Linux FTP Directory : /home/LinuxFolder/
Is it correct to write the code below like this?
string uploadUrl = "ftp://32.785.25.32/home/LinuxFolder/LinuxFile.txt";

Question-2) Destination Linux FTP Directory Folder Create
string DestinationFolderPath = "ftp://32.785.25.32/home/LinuxFolder";
DirectoryInfo di = new DirectoryInfo(DestinationFolderPath);
if (di.Exists == false)
{
di.Create();
}
Is it correct to write the code below like this?


C#:
public void FtpUpload()
{
   // STEP1) Destination Linux FTP Directory Folder Create
   string DestinationFolderPath = "ftp://32.785.25.32/home/LinuxFolder";
   DirectoryInfo di = new DirectoryInfo(DestinationFolderPath);
   if (di.Exists == false)
   {
        di.Create();
   }

   // STEP2) Destination Linux FTP Directory
    string uploadUrl = "ftp://32.785.25.32/home/LinuxFolder/LinuxFile.txt";

    FtpWebRequest request = (FtpWebRequest) WebRequest.Create(uploadUrl);
    request.Method = WebRequestMethods.Ftp.UploadFile;
  
    // This example assumes the FTP site uses anonymous logon.
    request.Credentials = new NetworkCredential("username", "password");
    request.Proxy = null;
    request.KeepAlive = true;
    request.UseBinary = true;
    request.Method = WebRequestMethods.Ftp.UploadFile;

    // Copy the contents of the file to the request stream.
    StreamReader sourceStream = new StreamReader(@"D:\Sapmle applications\TotalAmount.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);
}
 
Last edited:
For your question 1 and 2: Yes that is the correct URL. But DirectoryInfo() does not accept URLs so you can't use it to check to see if the path exists or create the directory on the destination machine.
 

Latest posts

Back
Top Bottom