FileNotFoundException With FTP - c#

I am trying to upload files more than one but I am just trying single fileupload for practice but I am getting file not found exception my task is as under.
private static void UploadFileToFtp(string source)
{
String ftpurl = #"ftp://ftp.yuvarukhisamaj.com/wwwroot/Shtri/"; //“#ftpurl”; // e.g. ftp://serverip/foldername/foldername
String ftpusername = "yuvarukh";//“#ftpusername”; // e.g. username
String ftppassword = "CXhV5Rzeu";//“#ftppassword”; // e.g. password
try
{
string filename = Path.GetFileName(source);
string ftpfullpath = ftpurl;
FtpWebRequest ftp = (FtpWebRequest)FtpWebRequest.Create(ftpfullpath);
ftp.Credentials = new NetworkCredential(ftpusername, ftppassword);
ftp.KeepAlive = true;
ftp.UseBinary = true;
ftp.Method = WebRequestMethods.Ftp.UploadFile;
FileStream fs = File.OpenRead(source);
byte[] buffer = new byte[fs.Length];
fs.Read(buffer, 0, buffer.Length);
fs.Close();
Stream ftpstream = ftp.GetRequestStream();
ftpstream.Write(buffer, 0, buffer.Length);
ftpstream.Close();
}
catch (Exception ex)
{
throw ex;
}
}
protected void Btn1_Click(object sender, EventArgs e)
{
String sourcefilepath = FileUpload1.FileName;
UploadFileToFtp(sourcefilepath);
}
Error Details is An Exception of type “System.IO.FileNotFoundException” Occurred in Bshadow.DLL but was not handle in usercode.
Additional information: could not find file C:\Programfiles\Microsoft Visual Studio 8\IDE\dd.jpg
How can I upload multiple files with fileUploaders Via FTP?

you need to use ad ftpurl address the folder/file.ext to upload
Also you use a simple exception you must handling exactly exception not generally one.
in example your full path for ftp must be :
#"ftp://ftp.yuvarukhisamaj.com/wwwroot/Shtri/" + filename + ext;
//ftp://ftp.yuvarukhisamaj.com/wwwroot/Shtri/yourimage.ext;
that fix your issue.
it is a common error in ftpclass of net.

Related

FTP FtpWebRequest uploader corrupting exe files

I have a simple FTP uploader (mostly not my own code, still learning)
It works just fine but it is corrupting exe files, from my reading around that is because it's not a binary reader. But what is confusing is that I am telling it to use binary.
This is my code:
private void UploadFileToFTP(string source)
{
String sourcefilepath = textBox5.Text;
String ftpurl = textBox3.Text; // e.g. ftp://serverip/foldername/foldername
String ftpusername = textBox1.Text; // e.g. username
String ftppassword = textBox2.Text; // e.g. password
try
{
string filename = Path.GetFileName(source);
string ftpfullpath = ftpurl + "/" + new FileInfo(filename).Name;
FtpWebRequest ftp = (FtpWebRequest)FtpWebRequest.Create(ftpfullpath);
ftp.Credentials = new NetworkCredential(ftpusername, ftppassword);
ftp.KeepAlive = true;
ftp.UseBinary = true;
ftp.Method = WebRequestMethods.Ftp.UploadFile;
FileStream fs = File.OpenRead(source);
byte[] buffer = new byte[fs.Length];
fs.Read(buffer, 0, buffer.Length);
fs.Close();
Stream ftpstream = ftp.GetRequestStream();
ftpstream.Write(buffer, 0, buffer.Length);
ftpstream.Close();
}
catch (Exception ex)
{
throw ex;
}
}
Stream.Read does not guarantee you to read all bytes you have requested.
Specifically FileStream.Read documentation says:
count: The maximum number of bytes to read.
Return Value: The total number of bytes read into the buffer. This might be less than the number of bytes requested if that number of bytes are not currently available, or zero if the end of the stream is reached.
To read whole file to memory, use File.ReadAllBytes:
byte[] buffer = File.ReadAllBytes(source);
Though you should actually use Stream.CopyTo, to avoid storing huge files completely to memory:
fs.CopyTo(ftp.GetRequestStream());
Not sure what issue you're having.
This code works just fine for me:
String sourcefilepath = "";
String ftpurl = ""; // e.g. ftp://serverip/foldername/foldername
String ftpusername = ""; // e.g. username
String ftppassword = ""; // e.g. password
var filePath = "";
try
{
string filename = Path.GetFileName(sourcefilepath);
string ftpfullpath = ftpurl + "/" + new FileInfo(filename).Name;
FtpWebRequest ftp = (FtpWebRequest)FtpWebRequest.Create(ftpfullpath);
ftp.Credentials = new NetworkCredential(ftpusername, ftppassword);
ftp.KeepAlive = true;
ftp.UseBinary = true;
ftp.Method = WebRequestMethods.Ftp.UploadFile;
byte[] buffer = File.ReadAllBytes(sourcefilepath);
ftp.ContentLength = buffer.Length;
Stream ftpstream = ftp.GetRequestStream();
ftpstream.Write(buffer, 0, buffer.Length);
ftpstream.Close();
}
catch (Exception ex)
{
throw ex;
}

C# - Download Directory - FTP

I'm trying to download a directory, using FTP in a C# application. I basically need to take a remote dir, and move it, and its contents into a local dir.
Here is the function I'm currently using, and what the log output and errors are. The sample I'm referencing is for getting files, and possibly not directories:
private void Download(string file, string destination)
{
try
{
string getDir = "ftp://" + ftpServerIP + ftpPath + file + "/";
string putDir = destination + "\\" + file;
Debug.WriteLine("GET: " + getDir);
Debug.WriteLine("PUT: " + putDir);
FtpWebRequest reqFTP;
reqFTP = (FtpWebRequest)FtpWebRequest.Create
(new Uri(getDir));
reqFTP.Credentials = new NetworkCredential(ftpUserID,
ftpPassword);
reqFTP.UseBinary = true;
reqFTP.KeepAlive = false;
reqFTP.Method = WebRequestMethods.Ftp.DownloadFile;
reqFTP.Proxy = null;
reqFTP.UsePassive = false;
FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();
Stream responseStream = response.GetResponseStream();
FileStream writeStream = new FileStream(putDir, FileMode.Create);
int Length = 2048;
Byte[] buffer = new Byte[Length];
int bytesRead = responseStream.Read(buffer, 0, Length);
while (bytesRead > 0)
{
writeStream.Write(buffer, 0, bytesRead);
bytesRead = responseStream.Read(buffer, 0, Length);
}
writeStream.Close();
response.Close();
}
catch (WebException wEx)
{
MessageBox.Show(wEx.Message, "Download Error");
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Download Error");
}
}
Debug:
GET: ftp://I.P.ADDR/SOME_DIR.com/members/forms/THE_FOLDER_TO_GET/
PUT: C:\Users\Public\Documents\iMacros\Macros\THE_FOLDER_TO_WRITE
A first chance exception of type 'System.Net.WebException' occurred in System.dll
MessageBox Output:
The requested URI is invalid for this FTP command.
The slash on the end of the getDir indicates a directory - can you use mget and pass a path like that ends in "/*"?

How to upload photo to a server from .net winforms?

I have created a window form application in C#. There is a user registration section where user details are filled and a photo is uploaded. How to upload photo a common location in server not in client system. I need to upload the picture of user to a location in server so that the website section of the application can show the picture in the profile of user.
I would actually store the information including the picture in the database, so it's available from all your other applications.
if you simply want to copy a raw file from client computer to a centralized location, as a starting point:
private void button1_Click(object sender, EventArgs e)
{
WebClient myWebClient = new WebClient();
string fileName = textBox1.Text;
string _path = Application.StartupPath;
MessageBox.Show(_path);
_path = _path.Replace("Debug", "Images");
MessageBox.Show(_path);
myWebClient.UploadFile(_path,fileName);
}
private void btnBrowse_Click(object sender, EventArgs e)
{
OpenFileDialog ofDlg = new OpenFileDialog();
ofDlg.Filter = "JPG|*.jpg|GIF|*.gif|PNG|*.png|BMP|*.bmp";
if (DialogResult.OK == ofDlg.ShowDialog())
{
textBox1.Text = ofDlg.FileName;
button1.Enabled = true;
}
else
{
MessageBox.Show("Go ahead, select a file!");
}
}
Maybe best way is to use an FTP Server ,if you can install it .
Than you can upload file's using this code
FileInfo toUpload = new FileInfo("FileName");
System.Net.FtpWebRequest request = (FtpWebRequest)WebRequest.Create("ftp://serverip/FileName");
request.Method = WebRequestMethods.Ftp.UploadFile;
request.Credentials = new NetworkCredential("UserName","Password");
Stream ftpStream = request.GetRequestStream();
FileStream file = File.OpenRead(files);
int length = 1024;
byte[] buffer = new byte[length];
int bytesRead = 0;
do
{
bytesRead = file.Read(buffer, 0, length);
ftpStream.Write(buffer, 0, bytesRead);
}
while (bytesRead != 0);
file.Close();
ftpStream.Close();
upload a file to FTP server using C# from our local hard disk.
private void UploadFileToFTP()
{
FtpWebRequest ftpReq = (FtpWebRequest)WebRequest.Create("ftp://www.server.com/sample.txt");
ftpReq.UseBinary = true;
ftpReq.Method = WebRequestMethods.Ftp.UploadFile;
ftpReq.Credentials = new NetworkCredential("user", "pass");
byte[] b = File.ReadAllBytes(#"E:\sample.txt");
ftpReq.ContentLength = b.Length;
using (Stream s = ftpReq.GetRequestStream())
{
s.Write(b, 0, b.Length);
}
FtpWebResponse ftpResp = (FtpWebResponse)ftpReq.GetResponse();
if (ftpResp != null)
{
if(ftpResp.StatusDescription.StartsWith("226"))
{
Console.WriteLine("File Uploaded.");
}
}
}

c# asp.net FTP Error

I get "System.NotSupportedException: The given path's format is not supported. at System.Security.Util.StringExpressionSet" when trying to download an item from an ftp(which have access to). The upload seems to work fine and is done similarly I'll post both functions below:
private void Download(string filePath, string fileName)
{
FtpWebRequest reqFTP;
try
{
//filePath = <<The full path where the file is to be created. the>>,
//fileName = <<Name of the file to be createdNeed not name on FTP server. name name()>>
Label1.Text = filePath + "/" + fileName;
FileStream outputStream = new FileStream(filePath + "/" + fileName, FileMode.Create);
reqFTP = (FtpWebRequest)FtpWebRequest.Create(new
Uri("ftp://" + ftpServerIP + "/" + fileName));
reqFTP.Method = WebRequestMethods.Ftp.DownloadFile;
reqFTP.UseBinary = true;
reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword);
FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();
Stream ftpStream = response.GetResponseStream();
long cl = response.ContentLength;
int bufferSize = 2048;
int readCount;
byte[] buffer = new byte[bufferSize];
readCount = ftpStream.Read(buffer, 0, bufferSize);
while (readCount > 0)
{
outputStream.Write(buffer, 0, readCount);
readCount = ftpStream.Read(buffer, 0, bufferSize);
}
ftpStream.Close();
outputStream.Close();
response.Close();
}
catch (Exception ex)
{
Label1.Text = ex.ToString();
}
}
public void Upload(string filename)
{
FileInfo fileInf = new FileInfo(filename);
string uri = "ftp://" + ftpServerIP + "/" + fileInf.Name;
FtpWebRequest reqFTP;
// Create FtpWebRequest object from the Uri provided
reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri("ftp://" + ftpServerIP +"/" + fileInf.Name));
// Provide the WebPermission Credintials
reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword);
// By default KeepAlive is true, where the control connection is not closed
// after a command is executed.
reqFTP.KeepAlive = false;
// Specify the command to be executed.
reqFTP.Method = WebRequestMethods.Ftp.UploadFile;
// Specify the data transfer type.
reqFTP.UseBinary = true;
// Notify the server about the size of the uploaded file
reqFTP.ContentLength = fileInf.Length;
// The buffer size is set to 2kb
int buffLength = 2048;
byte[] buff = new byte[buffLength];
int contentLen;
// Opens a file stream (System.IO.FileStream) to read the file to be uploaded
FileStream fs = fileInf.OpenRead();
try
{
// Stream to which the file to be upload is written
Stream strm = reqFTP.GetRequestStream();
// Read from the file stream 2kb at a time
contentLen = fs.Read(buff, 0, buffLength);
// Till Stream content ends
while (contentLen != 0)
{
// Write Content from the file stream to the FTP Upload Stream
strm.Write(buff, 0, contentLen);
contentLen = fs.Read(buff, 0, buffLength);
}
// Close the file stream and the Request Stream
strm.Close();
fs.Close();
}
catch (Exception ex)
{
//MessageBox.Show(ex.Message, "Upload Error");
}
}
and these are the function calls
protected void btnDownload_Click(object sender, EventArgs e)
{
string FullServer = "ftp://" + ftpServerIP;
Download(FullServer, LbxServer.SelectedValue);
}
protected void btnUpload_Click(object sender, EventArgs e)
{
Upload(LbxLocal.SelectedValue);
}
Thank you all for any help on this matter.
I think you'll find that ftp://myservername is an invalid scheme for a new FileStream. Note that your FileStream represents the local target, not the remote file.
If your intent is to download a remote file to your local system, filePath should refer to a folder on your local network (e.g., C:\temp or \\somecomputer\share, etc.)

Upload a file with encoding using FTP in C#

The following code is good for uploading text files, but it fails to upload JPEG files (not completely - the file name is good but the image is corrupted):
private void up(string sourceFile, string targetFile)
{
try
{
string ftpServerIP = ConfigurationManager.AppSettings["ftpIP"];
string ftpUserID = ConfigurationManager.AppSettings["ftpUser"];
string ftpPassword = ConfigurationManager.AppSettings["ftpPass"];
//string ftpURI = "";
string filename = "ftp://" + ftpServerIP + "//" + targetFile;
FtpWebRequest ftpReq = (FtpWebRequest)WebRequest.Create(filename);
ftpReq.Method = WebRequestMethods.Ftp.UploadFile;
ftpReq.Credentials = new NetworkCredential(ftpUserID, ftpPassword);
StreamReader stream = new StreamReader(sourceFile);
Byte[] b = System.Text.Encoding.UTF8.GetBytes(stream.ReadToEnd());
stream.Close();
ftpReq.ContentLength = b.Length;
Stream s = ftpReq.GetRequestStream();
s.Write(b, 0, b.Length);
s.Close();
System.Net.FtpWebResponse ftpResp = (FtpWebResponse)ftpReq.GetResponse();
MessageBox.Show(ftpResp.StatusDescription);
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
I have another solution that can upload a file:
private void Upload(string sourceFile, string targetFile)
{
string ftpUserID;
string ftpPassword;
string ftpServerIP;
ftpServerIP = ConfigurationManager.AppSettings["ftpIP"];
ftpUserID = ConfigurationManager.AppSettings["ftpUser"];
ftpPassword = ConfigurationManager.AppSettings["ftpPass"];
FileInfo fileInf = new FileInfo(sourceFile);
FtpWebRequest reqFTP;
// Create FtpWebRequest object from the Uri provided
reqFTP = (FtpWebRequest)(FtpWebRequest.Create(new Uri("ftp://" + ftpServerIP + "//" + targetFile)));
// Provide the WebPermission Credintials
reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword);
// Bypass default lan settings
reqFTP.Proxy = null;
// By default KeepAlive is true, where the control connection is not closed
// after a command is executed.
reqFTP.KeepAlive = false;
// Specify the command to be executed.
reqFTP.Method = WebRequestMethods.Ftp.UploadFile;
// Specify the data transfer type.
reqFTP.UseBinary = true;
// Notify the server about the size of the uploaded file
reqFTP.ContentLength = fileInf.Length;
// The buffer size is set to 2kb
int buffLength = 2048;
Byte[] buff;
buff = new byte[buffLength];
int contentLen;
// Opens a file stream (System.IO.FileStream) to read the file to be uploaded
FileStream fs = fileInf.OpenRead();
try
{
// Stream to which the file to be upload is written
Stream strm = reqFTP.GetRequestStream();
// Read from the file stream 2kb at a time
long filesize = fs.Length;
int i=0;
contentLen = fs.Read(buff, 0, buffLength);
// Till Stream content ends
while (contentLen != 0)
{
Application.DoEvents();
// Write Content from the file stream to the FTP Upload Stream
strm.Write(buff, 0, contentLen);
contentLen = fs.Read(buff, 0, buffLength);
i = i + 1;
//Double percentComp = (i * buffLength) * 100 / filesize;
//ProgressBar1.Value = (int)percentComp;
}
// Close the file stream and the Request Stream
strm.Close();
fs.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Upload Error");
}
}
But here I have the opposite problem - the picture is good, but the file name is corrupted.
I know it is because of the encoding, but I don't know how to make the bytes array have the desired encoding...
Try this bit:
private static void up(string sourceFile, string targetFile)
{
try
{
string ftpServerIP = ConfigurationManager.AppSettings["ftpIP"];
string ftpUserID = ConfigurationManager.AppSettings["ftpUser"];
string ftpPassword = ConfigurationManager.AppSettings["ftpPass"];
////string ftpURI = "";
string filename = "ftp://" + ftpServerIP + "//" + targetFile;
FtpWebRequest ftpReq = (FtpWebRequest)WebRequest.Create(filename);
ftpReq.UseBinary = true;
ftpReq.Method = WebRequestMethods.Ftp.UploadFile;
ftpReq.Credentials = new NetworkCredential(ftpUserID, ftpPassword);
byte[] b = File.ReadAllBytes(sourceFile);
ftpReq.ContentLength = b.Length;
using (Stream s = ftpReq.GetRequestStream())
{
s.Write(b, 0, b.Length);
}
FtpWebResponse ftpResp = (FtpWebResponse)ftpReq.GetResponse();
if (ftpResp != null)
{
MessageBox.Show(ftpResp.StatusDescription);
}
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
You should be using a Stream to read binary files, not a StreamReader. StreamReader is designed to read text files only.
In your first code example, enable binary transfer: FtpWebRequest.UseBinary = true. Otherwise it will convert what it thinks are textual line endings between the various platform conventions (but are actually part of the image).
Your second snippet does it the right way. It uses FileStream, not StreamReader. StreamReader is only suitable for text files.
System.Text.Encoding.UTF8.GetBytes(stream.ReadToEnd());
Don't do this unless your stream's contents are text. Change your function to accept a boolean parameter "binary", and use the latter, working method if that flag is set.
If you have this problem: The requested FTP command is not supported when using HTTP
you need set proxy in Null or Nothing.
ftpReq.Proxy = null;
You can see this blog.
http://mycodetrip.com/2008/10/29/fix-for-error-the-requested-ftp-command-is-not-supported-when-using-http-proxy_118/comment-page-1/#comment-2825
Thanks.

Categories