Code Snippet: Upload via FTP with .NET v2
Here is a quick code snippet of uploading a file from the local disk, via FTP.
//get the contents of the file you want to upload byte[] fileContents;string FinalFile = @"c:\autoexec.bat";
using(System.IO.FileStream fs = new System.IO.FileStream(FinalFile, System.IO.FileMode.Open)) {fileContents =
new byte[fs.Length]; fs.Read(fileContents, 0, (int)fs.Length);}
//get the filename, append it to the URLSystem.IO.FileInfo fi = new System.IO.FileInfo(FinalFile); //FTPServerURI must be in the format of: //ftp://user:password@ftp.myserver.com:21/path/to/upload/folder/string uri = string.Format("{0}{1}", FTPServerURI, fi.Name); //now we have: //ftp://user:password@ftp.myserver.com:21/path/to/upload/folder/autoexec.bat //create the ftp requestSystem.Net.WebRequest request = System.Net.FtpWebRequest.Create(uri); //state that we uploading the filerequest.Method = System.Net.WebRequestMethods.Ftp.UploadFile; //get the request streamusing (System.IO.Stream stm = request.GetRequestStream()) { //write the contents of the file upstm.Write(zipContents, 0, zipContents.Length);
}
6 Comments
Comments have been disabled for this content.
Bart said
Hi, You declare "byte[] fileContents;", but while uploading you use "zipContents". Is this one just a simple typo ? Or am I missing something ? Regards, Bart,
Richard said
Rather than manually reading the file with a FileStream, you can simply use: byte[] fileContents = System.IO.File.ReadAllBytes(FinalFile); Also, rather than creating a FileInfo simply to extract the file name, you can use the System.IO.Path.GetFileName method: string uri = string.Format("{0}{1}", FTPServerURI, System.IO.Path.GetFileName(FinalFile));
ayşe nur said
hello; i tried the code above and got the errors below;could you please help me : 1-The name 'FTPServerURI' does not exist in the current context 2-The name 'zipContents' does not exist in the current context
Robb said
Hey! Do you use Twitter? I'd like to follow you if that would be ok. I'm undoubtedly enjoying your blog and look forward to new posts.
Watters said
Good article. I am dealing with a few of these issues as well. .
Fontenot said
Hurrah! After all I got a web site from where I
know how to actually obtain useful facts regarding my study and knowledge.