difference between uploadfile and uploadfilewithuniquename in WebRequestMethods.Ftp - c#

Two questions here :
1)difference between WebRequestMethods.Ftp.uploadfile and WebRequestMethods.Ftp.uploadfilewithuniquename?
2)When i do an upload file using the code below for an already existing file would it override the file.And is it safe to assume that it would always override?
public static void Main ()
{
// Get the object used to communicate with the server.
FtpWebRequest request = (FtpWebRequest)WebRequest.Create("ftp://www.contoso.com/test.htm");
request.Method = WebRequestMethods.Ftp.UploadFile;
// what if i use request.Method = WebRequestMethods.Ftp.UploadFilewithuniquename;
// This example assumes the FTP site uses anonymous logon.
request.Credentials = new NetworkCredential ("anonymous","janeDoe#contoso.com");
// Copy the contents of the file to the request stream.
StreamReader sourceStream = new StreamReader("testfile.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();
}

These methods refer to the FTP commands STOR and STOU.
If the logged in user has the privs, then STOR (WebRequestMethods.Ftp.UploadFile) will create a new file or overwrite an existing file.

Related

C#: ftp upload is successful but dowloaded file is damaged

I'm using the code bellow to upload a zip file to to my ftp server:
string zipPath = #"d:\files\start.zip";
string ftpPath = ("ftp://######/start.zip");
WebRequest request = WebRequest.Create(ftpPath);
request.Method = WebRequestMethods.Ftp.UploadFile;
request.Credentials = new NetworkCredential("######", "######");
StreamReader sourceStream = new StreamReader(zipPath);
byte[] fileContents = Encoding.Unicode.GetBytes(sourceStream.ReadToEnd());
sourceStream.Close();
request.ContentLength = fileContents.Length;
try
{
Stream requestStream = request.GetRequestStream();
requestStream.Write(fileContents, 0, fileContents.Length);
requestStream.Close();
FtpWebResponse makeFileUploadResponse = (FtpWebResponse)request.GetResponse();
}
catch
{
MessageBox.Show("ftp failed!");
}
My zip archive is definitely valid (I can open it and extract it) but when I download the uploaded zip file, I got the error that archive is damaged.
Update 1: my source code is from MSDN article:How to: Upload Files with FTP
you should cast request to FtpWebRequest (as in that MSDN example)
and then specify request as binary (you're uploading binary file, not text).
FtpWebRequest request = (FtpWebRequest)WebRequest.Create("aa");
request.Method = WebRequestMethods.Ftp.UploadFile;
request.UseBinary = true;
I can't say what the problem is but I can provide an alternate solution. You can use WebClient instead of WebRequest
string zipPath = #"d:\files\start.zip";
string ftpPath = ("ftp://######/start.zip");
WebClient ftpClient = new WebClient();
ftpClient.Credentials = new NetworkCredential("####", "######");
try{
ftpClient.UploadFile(ftpPath, WebRequestMethods.Ftp.AppendFile, zipPath);
}
catch(WebException ex){
MessageBox.Show("ftp failed");
}

Upload Multiple Ftp Files once

Im working at C#, I have 4 files, How to upload them all at once?
I have this, But this only works at 1 file.
FtpWebRequest request = (FtpWebRequest)WebRequest.Create("(secret)/keystock1.txt");
request.Method = WebRequestMethods.Ftp.UploadFile;
// This example assumes the FTP site uses anonymous logon.
request.Credentials = new NetworkCredential("secret", "secret");
// Copy the contents of the file to the request stream.
StreamReader sourceStream = new StreamReader("keystock1.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("STOCK Upload File Complete, status {0}", response.StatusDescription);
response.Close();
You can achieve this using Async tasks. A class like following would achieve this:
public class FileUploadsManager
{
//pass in the list of file paths which u want to upload.
public static async void UploadFilesAsync(string[] filePaths)
{
List<Task> fileUploadingTasks = new List<Task>();
foreach (var filePath in filePaths)
{
fileUploadingTasks.Add(UploadFileAsync(filePath));
}
await Task.WhenAll(fileUploadingTasks);
}
public static Task UploadFileAsync(string filePath)
{
return Task.Run(async () =>
{
//this is your code with a few changes
FtpWebRequest request = (FtpWebRequest)WebRequest.Create(
string.Format("(secret)/{0}", Path.GetFileName(filePath))
);
request.Method = WebRequestMethods.Ftp.UploadFile;
// This example assumes the FTP site uses anonymous logon.
request.Credentials = new NetworkCredential("secret", "secret");
// Copy the contents of the file to the request stream.
StreamReader sourceStream = new StreamReader(filePath);
byte[] fileContents = Encoding.UTF8.GetBytes(await sourceStream.ReadToEndAsync());
sourceStream.Close();
request.ContentLength = fileContents.Length;
Stream requestStream = await request.GetRequestStreamAsync();
requestStream.Write(fileContents, 0, fileContents.Length);
requestStream.Close();
FtpWebResponse response = (FtpWebResponse)await request.GetResponseAsync();
Console.WriteLine("STOCK Upload File Complete, status {0}", response.StatusDescription);
response.Close();
});
}
}
You can call this as follows:
string[] paths = new string[] { "C:\file1.txt", "C:\file2.txt", "C:\file2.txt" };
FileUploadsManager.UploadFilesAsync(paths);

How to send an excel file to FTP using C#?

I using the following code to send an excel file to FTP. File is sending, File size is also same. But file contains only spaces.
ftpAddress = "X.X.X.X";
outFilePath = "MyFolder/Sample.xls";
inFilePath = "D:/Hello.xls";
FtpWebRequest request = (FtpWebRequest)WebRequest.Create("ftp://" + ftpAddress + "/" + outFilePath);
request.Method = WebRequestMethods.Ftp.UploadFile;
request.UseBinary = true;
request.UsePassive = true;
request.KeepAlive = true;
request.Credentials = new NetworkCredential(userId, password);
//FileStream stream = File.OpenRead(inFilePath);
byte[] fileContents = File.ReadAllBytes(inFilePath);
//byte[] buffer = new byte[stream.Length];
request.ContentLength = fileContents.Length;
Stream requestStream = request.GetRequestStream();
requestStream.Write(fileContents, 0, fileContents.Length);
requestStream.Close();
//Shows confirm message
FtpWebResponse response = (FtpWebResponse)request.GetResponse();
Console.WriteLine(response);
response.Close();
Please help. Thanks in advance.
Source: http://msdn.microsoft.com/en-us/library/ms229715(v=vs.110).aspx
using System;
using System.IO;
using System.Net;
using System.Text;
namespace Examples.System.Net
{
public class WebRequestGetExample
{
public static void Main ()
{
// Get the object used to communicate with the server.
FtpWebRequest request = (FtpWebRequest)WebRequest.Create("ftp://www.contoso.com/test.htm");
request.Method = WebRequestMethods.Ftp.UploadFile;
// This example assumes the FTP site uses anonymous logon.
request.Credentials = new NetworkCredential ("anonymous","janeDoe#contoso.com");
// Copy the contents of the file to the request stream.
StreamReader sourceStream = new StreamReader("testfile.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();
}
}
}
}

C# FTP Uload Acces denied Error 550

My Class FTP work fine wtih my FTP server, but not with my client FTP server.
public class UploadToFTP
{
public void UploadFTP(string LeSource, string Desti, string CodeClient)
{
Pers_Conf oConf = LeConf.Get_Config(CodeClient);
// Get the object used to communicate with the server.
FtpWebRequest request = (FtpWebRequest)WebRequest.Create("ftp://" + oConf.FtpServer + oConf.FtpChemin +"/" + Desti);
request.Method = WebRequestMethods.Ftp.UploadFile;
// This example assumes the FTP site uses anonymous logon.
request.Credentials = new NetworkCredential(oConf.FtpLogin, oConf.FtpPwd);
request.UseBinary = true;
request.UsePassive = true;
// Copy the contents of the file to the request stream.
StreamReader sourceStream = new StreamReader(LeSource);
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();
}
}
this line is not work : Stream requestStream = request.GetRequestStream();
Anybody have solution ?
i have change the right into 777.
Thanks you in advance,
Stev
The Solutions
/ work only several ftp servers, but // it works perfectly everywhere

FtpWebRequest not downloading more then 8820 bytes of data

I am trying to transfer files between a couple of sites and I'm using FtpWebRequest to download the file from site A and upload it to site B.
The problem I'm facing is when I am downloading the file I'm not getting more then 8820 bytes of data.
Heres the code I am using:
public FtpFile Download(string path)
{
string fullpath = ConstructFullpath(path);
FtpWebRequest request = (FtpWebRequest)WebRequest.Create(fullpath);
request.Method = WebRequestMethods.Ftp.DownloadFile;
// login
request.Credentials = new NetworkCredential(Username, Password);
FtpWebResponse response = (FtpWebResponse)request.GetResponse();
Stream responseStream = request.GetResponse().GetResponseStream();
byte[] data = new byte[20000];
int length = responseStream.Read(data, 0, data.Length);
responseStream.Close();
FtpFile file = new FtpFile(path, data, length);
return file;
}
public bool Upload(FtpFile file)
{
if (!DirectoryExists(GetDirectory(file.Path)))
{
CreateDirectory(GetDirectory(file.Path));
}
string fullpath = ConstructFullpath(file.Path);
FtpWebRequest request = (FtpWebRequest)WebRequest.Create(fullpath);
request.Method = WebRequestMethods.Ftp.UploadFile;
request.Credentials = new NetworkCredential(Username, Password);
Stream stream = request.GetRequestStream();
stream.Write(file.Data, 0, file.Length);
stream.Close();
FtpWebResponse response = (FtpWebResponse)request.GetResponse();
return true;
}
The First image shows the source directory.
The second image shows the destination directory.
I have tried saving the files locally and have the same result.
You're only calling Read once:
byte[] data = new byte[20000];
int length = responseStream.Read(data, 0, data.Length);
responseStream.Close();
There's no guarantee that all the data will be read in a single call, and you should never rely on it doing so. You should loop round (e.g. copying the data into a MemoryStream) until Read returns 0.
If you're using .NET 4, Stream.CopyTo makes this easy:
MemoryStream ms = new MemoryStream();
responseStream.CopyTo(ms);
Note that you should also use using statements instead of closing resources explicitly, and that includes the FtpWebResponse.

Categories