C# How to upload large files to ftp site - c#

I am developing an windows application for backup(Files and sql server database).
Now i need to upload these files(.rar files) to my ftp site.
For uploading i use this code.
Code
string file = "D:\\RP-3160-driver.zip";
//opening the file for read.
string uploadFileName = "", uploadUrl = "";
uploadFileName = new FileInfo(file).Name;
uploadUrl = "ftp://ftp.Sitename.com/tempFiles/";
FileStream fs = new FileStream(file, FileMode.Open, FileAccess.Read);
try
{
long FileSize = new FileInfo(file).Length; // File size of file being uploaded.
Byte[] buffer = new Byte[FileSize];
fs.Read(buffer, 0, buffer.Length);
fs.Close();
fs = null;
string ftpUrl = string.Format("{0}/{1}", uploadUrl, uploadFileName);
FtpWebRequest requestObj = FtpWebRequest.Create(ftpUrl) as FtpWebRequest;
requestObj.Method = WebRequestMethods.Ftp.UploadFile;
requestObj.Credentials = new NetworkCredential("usernam", "password");
Stream requestStream = requestObj.GetRequestStream();
requestStream.Write(buffer, 0, buffer.Length);
requestStream.Flush();
requestStream.Close();
requestObj = null;
MessageBox.Show("File upload/transfer Successed.", "Successed", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
catch (Exception ex)
{
if (fs != null)
{
fs.Close();
}
MessageBox.Show("File upload/transfer Failed.\r\nError Message:\r\n" + ex.Message, "Successed", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
This code uploads only those files which has size < 5 Mb.
But i need to upload larger then 500Mb to 1Gb files.
So can any one help me.

For larger files you may choose to read the file stream and write it to the output stream as you read it.
FileStream fs = null;
Stream rs = null;
try
{
string file = "D:\\RP-3160-driver.zip";
string uploadFileName = new FileInfo(file).Name;
string uploadUrl = "ftp://ftp.Sitename.com/tempFiles/";
fs = new FileStream(file, FileMode.Open, FileAccess.Read);
string ftpUrl = string.Format("{0}/{1}", uploadUrl, uploadFileName);
FtpWebRequest requestObj = FtpWebRequest.Create(ftpUrl) as FtpWebRequest;
requestObj.Method = WebRequestMethods.Ftp.UploadFile;
requestObj.Credentials = new NetworkCredential("usernam", "password");
rs = requestObj.GetRequestStream();
byte[] buffer = new byte[8092];
int read = 0;
while ((read = fs.Read(buffer, 0, buffer.Length)) != 0)
{
rs.Write(buffer, 0, read);
}
rs.Flush();
}
catch (Exception exception)
{
MessageBox.Show("File upload/transfer Failed.\r\nError Message:\r\n" + exception.Message, "Succeeded", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
finally
{
if (fs != null)
{
fs.Close();
fs.Dispose();
}
if (rs != null)
{
rs.Close();
rs.Dispose();
}
}

Stream class has a nice Method CopyTo.
You don't need to read and write from/to streams. Just use fs.CopyTo(requestStream);
With this method, you don't have to declare large arrays like new Byte[FileSize];

Related

How set WebRequest stream share mode to share_read?

I use the following code from here to upload large files to ftp site.
As the file is uploaded to the server I go to the server with the RDP and can not open it because it is being used by another process.
My question is, can I set the file sharing mode so that I can read the file while writing? I want to read the uploaded file while it is being written.
FileStream fs = null;
Stream rs = null;
try
{
string file = "D:\\RP-3160-driver.zip";
string uploadFileName = new FileInfo(file).Name;
string uploadUrl = "ftp://ftp.Sitename.com/tempFiles/";
fs = new FileStream(file, FileMode.Open, FileAccess.Read);
string ftpUrl = string.Format("{0}/{1}", uploadUrl, uploadFileName);
FtpWebRequest requestObj = FtpWebRequest.Create(ftpUrl) as FtpWebRequest;
requestObj.Method = WebRequestMethods.Ftp.UploadFile;
requestObj.Credentials = new NetworkCredential("usernam", "password");
rs = requestObj.GetRequestStream();
byte[] buffer = new byte[8092];
int read = 0;
while ((read = fs.Read(buffer, 0, buffer.Length)) != 0)
{
rs.Write(buffer, 0, read);
}
rs.Flush();
}
catch (Exception e)
{
MessageBox.Show("File upload/transfer Failed.\r\nError Message:\r\n" + ex.Message, "Succeeded", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
finally
{
if (fs != null)
{
fs.Close();
fs.Dispose();
}
if (rs != null)
{
rs.Close();
rs.Dispose();
}
}
Try the following, I added FileShare.ReadWrite to the FileStream:
string file = "D:\\RP-3160-driver.zip";
string uploadFileName = new FileInfo(file).Name;
string uploadUrl = "ftp://ftp.Sitename.com/tempFiles/";
using (FileStream stream = File.Open(file, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
{
string ftpUrl = string.Format("{0}/{1}", uploadUrl, uploadFileName);
FtpWebRequest requestObj = FtpWebRequest.Create(ftpUrl) as FtpWebRequest;
requestObj.Method = WebRequestMethods.Ftp.UploadFile;
requestObj.Credentials = new NetworkCredential("usernam", "password");
using (Stream rs = requestObj.GetRequestStream())
{
stream.CopyTo(rs);
}
}

ASP.Net FTP Upload Not Working

I am trying to upload an image file via FTP in ASP.Net. The image file is uploaded to correct location but when I read or download it, it's corrupt. My code is given below
protected void FTPUpload()
{
//FTP Server URL.
string ftp = ConfigurationManager.AppSettings.Get("FTPServer");
//FTP Folder name.
string ftpFolder = "images/logos/";
//FTP Credentials
string ftpUsername = ConfigurationManager.AppSettings.Get("FTPUsername");
string ftpPassword = ConfigurationManager.AppSettings.Get("FTPPassword");
byte[] fileBytes = null;
//Read the FileName and convert it to Byte array.
string fileName = Path.GetFileName(fuLogo.FileName);
using (StreamReader fileStream = new StreamReader(fuLogo.PostedFile.InputStream))
{
fileBytes = Encoding.UTF8.GetBytes(fileStream.ReadToEnd());
fileStream.Close();
}
try
{
//Create FTP Request.
FtpWebRequest request = (FtpWebRequest)WebRequest.Create(ftp + ftpFolder + fileName);
request.Method = WebRequestMethods.Ftp.UploadFile;
//Enter FTP Server credentials.
request.Credentials = new NetworkCredential(ftpUsername, ftpPassword);
request.ContentLength = fileBytes.Length;
request.UsePassive = true;
request.UseBinary = true;
request.ServicePoint.ConnectionLimit = fileBytes.Length;
request.EnableSsl = false;
using (var requestStream = request.GetRequestStream())
{
CopyStream(fuLogo.PostedFile.InputStream, requestStream);
}
FtpWebResponse response = (FtpWebResponse)request.GetResponse();
//lblMessage.Text += fileName + " uploaded.<br />";
response.Close();
}
catch (WebException ex)
{
throw new Exception((ex.Response as FtpWebResponse).StatusDescription);
}
}
public static void CopyStream(Stream input, Stream output)
{
byte[] buffer = new byte[1024000];
int read;
while ((read = input.Read(buffer, 0, buffer.Length)) > 0)
{
output.Write(buffer, 0, read);
}
}
Am I missing something? The file is uploaded perfectly but for some reason it gets corrupted.
This part smells:
using (StreamReader fileStream = new StreamReader(fuLogo.PostedFile.InputStream))
{
fileBytes = Encoding.UTF8.GetBytes(fileStream.ReadToEnd());
fileStream.Close();
}
There should be no reason to first copy image to array (and use default text encoding/UTF8 decoding in the meantime) - just do stream-to-stream copy(see How do I copy the contents of one stream to another?):
public static void CopyStream(Stream input, Stream output)
{
byte[] buffer = new byte[32768];
int read;
while ((read = input.Read(buffer, 0, buffer.Length)) > 0)
{
output.Write (buffer, 0, read);
}
}
So the ftp upload should be just
using (var requestStream = request.GetRequestStream())
{
CopyStream(fuLogo.PostedFile.InputStream, requestStream);
// no need to requestStream.Close(); - using does that for you
}

C# - FTP transfer Access ACCDE files

I wrote a simple C# program to transfer ACCDE files from a FTP server to a client's desktop. The transferring seems to work fine, however, when I open the file and try to use the program, it gives me the message "Requested type library or wizard is not a VBA project."
When I transfer the ACCDB source code, it seems to work fine. This is the transfer function:
private void DownloadFileFTP(string fileName, string localFilePath, bool isXmlSchema)
{
string ftpFilePath = redacted;
if (isXmlSchema)
{
ftpFilePath = ftpFilePath + fileName;
label3.Text = "Fetching update information...";
}
else
{
ftpFilePath = ftpFilePath + Properties.Settings.Default.Customer + "/" + fileName;
label3.Text = "Updating " + fileName;
}
FtpWebRequest request = (FtpWebRequest)WebRequest.Create(ftpFilePath);
request.Credentials = new NetworkCredential(redacted, redacted);
request.Method = WebRequestMethods.Ftp.DownloadFile;
request.EnableSsl = Properties.Settings.Default.SSL;
request.UsePassive = Properties.Settings.Default.Passive;
int bytesRead = 0;
byte[] buffer = new byte[2048];
Stream reader = request.GetResponse().GetResponseStream();
FileStream fs = new FileStream(localFilePath, FileMode.Create);
while(true)
{
bytesRead = reader.Read(buffer, 0, buffer.Length);
if (bytesRead == 0)
break;
fs.Write(buffer, 0, bytesRead);
}
fs.Close();
}
My questions, I suppose, are: am I doing something wrong here? Do ACCDE files not play nice with FileStreams or something? I am still quite new to .NET so any help would be very appreciated.
EDIT: It seems one of the references was causing the problem.
You didn't close stream and ftpWebRequest.
Try this, made with you script, just copy/paste (fix some error if it have :) ):
private void DownloadFileFTP(string fileName, string localFilePath, bool isXmlSchema)
{
FileStream fs = null;
try
{
fileName = Regex.Replace(fileName.ToString(), #"\s.*$", "").Trim();
string ftpFilePath = redacted;
if (isXmlSchema)
{
ftpFilePath = ftpFilePath + fileName;
label3.Text = "Fetching update information...";
}
else
{
ftpFilePath = ftpFilePath + Properties.Settings.Default.Customer + "/" + fileName;
label3.Text = "Updating " + fileName;
}
FtpWebRequest request = (FtpWebRequest)WebRequest.Create(ftpFilePath);
request.Credentials = new NetworkCredential(redacted, redacted);
request.Method = WebRequestMethods.Ftp.DownloadFile;
request.EnableSsl = Properties.Settings.Default.SSL;
request.UsePassive = Properties.Settings.Default.Passive;
int bytesRead = 0;
int bufferSize = 2048;
byte[] buffer = new byte[bufferSize];
Stream reader = request.GetResponseStream();
bytesRead = reader.Read(buffer, 0, bufferSize);
fs = new FileStream(localFilePath, FileMode.Create);
while (bytesRead > 0)
{
fs.Write(buffer, 0, bytesRead);
bytesRead = reader.Read(buffer, 0, bufferSize);
}
reader.Close();
request.Close();
}
catch (Exception ex)
{
label3.Text = "Error: " + ex.ToString;
}
finally
{
if (fs != null)
{
fs.Close();
}
}
}

Upload large file to ftp C#

I'm uploading large files to ftp site using this code.
Code
using (FileStream fs = new FileStream(FileLoc, FileMode.Open, FileAccess.Read))
{
string ftpUrl = string.Format("{0}/{1}", uploadUrl, uploadFileName);
FtpWebRequest requestObj = FtpWebRequest.Create(ftpUrl) as FtpWebRequest;
requestObj.Method = WebRequestMethods.Ftp.UploadFile;
requestObj.Credentials = new NetworkCredential(Uid, Pass);
using (Stream requestStream = requestObj.GetRequestStream())
{
byte[] buffer = new byte[8092];
int read = 0;
while ((read = fs.Read(buffer, 0, buffer.Length)) != 0)
{
requestStream.Write(buffer, 0, read);
}
requestStream.Flush();
if (fs != null)
{
fs.Close();
fs.Dispose();
}
if (requestStream != null)
{
requestStream.Close();
requestStream.Dispose();
}
}
}
Some times this code up-lode files very fine but some time it up-lodes some part of file not complete file and doesn't give any error.
Can any one help me why some time it upload only some part of file not hole file.
Here's the code we use for uploading to FTP. It looks very similar to your own. Nevertheleess, I post it for your reference as we haven't had any such reported failures
private void UploadFile(string fileToUpload)
{
Output = new Uri(Path.Combine(Output.ToString(), Path.GetFileName(fileToUpload)));
FtpWebRequest request = WebRequest.Create(Output) as FtpWebRequest;
request.Method = WebRequestMethods.Ftp.UploadFile;
// in order to work with Microsoft Windows Server 2003 + IIS, we can't use passive mode.
request.UsePassive = false;
request.Credentials = new NetworkCredential(username, password);
// Copy the contents of the file to the request stream.
Stream dest = request.GetRequestStream();
FileStream src = File.OpenRead(fileToUpload);
int bufSize = (int)Math.Min(src.Length, 1024);
byte[] buffer = new byte[bufSize];
int bytesRead = 0;
int numBuffersUploaded = 0;
do
{
bytesRead = src.Read(buffer, 0, bufSize);
dest.Write(buffer, 0, bufSize);
numBuffersUploaded++;
}
while (bytesRead != 0);
dest.Close();
src.Close();
FtpWebResponse response = (FtpWebResponse)request.GetResponse();
if (response.StatusCode != FtpStatusCode.ClosingData)
{
Console.Error.WriteLine("Request {0}: Error uploading file to FTP server: {1} ({2})", Id, response.StatusDescription, response.StatusCode);
}
else
{
Console.Out.WriteLine("Request {0}: Successfully transferred file to {1}", Id, Output.ToString());
}
}

Can not delete the file after upload it to FTP by FtpWebRequest

Here is my code to upload a file :
FtpWebRequest reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(uri));
reqFTP.Credentials = new NetworkCredential("****", "*****");
reqFTP.Method = WebRequestMethods.Ftp.UploadFile;
reqFTP.KeepAlive = false;
reqFTP.UseBinary = true;
reqFTP.UsePassive = true;
reqFTP.ContentLength = stream.Length;
// reqFTP.EnableSsl = true; // it's FTPES type of ftp
int buffLen = 2048;
byte[] buff = new byte[buffLen];
int contentLen;
try
{
Stream ftpStream = reqFTP.GetRequestStream();
contentLen = stream.Read(buff, 0, buffLen);
while (contentLen != 0)
{
ftpStream.Write(buff, 0, contentLen);
contentLen = stream.Read(buff, 0, buffLen);
}
ftpStream.Flush();
ftpStream.Close();
ftpStream.Dispose();
}
catch (Exception exc)
{
return false;
}
//delete image from local
stream.Flush();
stream.Close();
stream.Dispose();
DeleteFile();
DeleteFile method try to delete the uploaded file; but it has an error that the file is being used by my app and so it can not delete it. Is there any one to help me about this issue?!
UPDATE1 :
private void DeleteFile()
{
DirectoryInfo DirInfo = new DirectoryInfo(#"Direectory Contains uploaded file");
foreach (FileInfo file in DirInfo.GetFiles())
{
file.Delete();
}
}
I assume you want to delete the local file? The error says the file is still in use. Wrap the code where you initalize the stream variable in a using block.

Categories