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.");
}
}
}
Related
The idea is that if I selected more than one file then upload one file when, then when it finishes to upload then upload the next one and so on.
I changed the filedialoug to be able to select multi:
private void btnBrowse_Click(object sender, EventArgs e)
{
openFileDialog1.Multiselect = true;
if (this.openFileDialog1.ShowDialog() != DialogResult.Cancel)
this.txtUploadFile.Text = this.openFileDialog1.FileName;
}
I can select more than one file the problem is that when using a breakpoint I see on this.txtUploadFile.Text one file only the first I selected. txtUploadFile is a textBox.
The first thing is: how can I see on the textBox(txtUploadFile) all the selected files and not only one? Or how can I get some indication that all the files I selected really selected? Maybe to show somehow in the textBox something that all files selected?
The important part is: how do I upload all the selected files one by one?
This is the button click event that starting the files uploading:
private void btnUpload_Click(object sender, EventArgs e)
{
if(this.ftpProgress1.IsBusy)
{
this.ftpProgress1.CancelAsync();
this.btnUpload.Text = "Upload";
}
else
{
FtpSettings f = new FtpSettings();
f.Host = this.txtHost.Text;
f.Username = this.txtUsername.Text;
f.Password = this.txtPassword.Text;
f.TargetFolder = this.txtDir.Text;
f.SourceFile = this.txtUploadFile.Text;
f.Passive = this.chkPassive.Checked;
try
{
f.Port = Int32.Parse(this.txtPort.Text);
}
catch { }
this.toolStripProgressBar1.Visible = true;
this.ftpProgress1.RunWorkerAsync(f);
this.btnUpload.Text = "Cancel";
}
}
I also have a backgroundworker with a progressBar so each file that is uploading the progressBar should show the progress of the uploading today it's showing for one file since I can upload only one file:
private void ftpProgress1_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
this.toolStripStatusLabel1.Text = e.UserState.ToString(); // The message will be something like: 45 Kb / 102.12 Mb
this.toolStripProgressBar1.Value = Math.Min(this.toolStripProgressBar1.Maximum, e.ProgressPercentage);
}
private void ftpProgress1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
if(e.Error != null)
MessageBox.Show(e.Error.ToString(), "FTP error");
else if(e.Cancelled)
this.toolStripStatusLabel1.Text = "Upload Cancelled";
else
this.toolStripStatusLabel1.Text = "Upload Complete";
this.btnUpload.Text = "Upload";
this.toolStripProgressBar1.Visible = true;
}
And last the class of the FTP uploader:
using System;
using System.ComponentModel;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Net;
using System.Text;
namespace FTP_ProgressBar
{
public partial class FtpProgress : BackgroundWorker
{
public static string ConnectionError;
private FtpSettings f;
public FtpProgress()
{
InitializeComponent();
}
public FtpProgress(IContainer container)
{
container.Add(this);
InitializeComponent();
}
private void FtpProgress_DoWork(object sender, DoWorkEventArgs e)
{
try
{
BackgroundWorker bw = sender as BackgroundWorker;
f = e.Argument as FtpSettings;
string UploadPath = String.Format("{0}/{1}{2}", f.Host, f.TargetFolder == "" ? "" : f.TargetFolder + "/", Path.GetFileName(f.SourceFile));
if (!UploadPath.ToLower().StartsWith("ftp://"))
UploadPath = "ftp://" + UploadPath;
FtpWebRequest request = (FtpWebRequest)WebRequest.Create(UploadPath);
request.UseBinary = true;
request.UsePassive = f.Passive;
request.Method = WebRequestMethods.Ftp.UploadFile;
request.Timeout = 300000;
request.Credentials = new NetworkCredential(f.Username, f.Password);
long FileSize = new FileInfo(f.SourceFile).Length;
string FileSizeDescription = GetFileSize(FileSize);
int ChunkSize = 4096, NumRetries = 0, MaxRetries = 50;
long SentBytes = 0;
byte[] Buffer = new byte[ChunkSize];
using (Stream requestStream = request.GetRequestStream())
{
using (FileStream fs = File.Open(f.SourceFile, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
{
int BytesRead = fs.Read(Buffer, 0, ChunkSize);
while (BytesRead > 0)
{
try
{
if (bw.CancellationPending)
return;
requestStream.Write(Buffer, 0, BytesRead);
SentBytes += BytesRead;
string SummaryText = String.Format("Transferred {0} / {1}", GetFileSize(SentBytes), FileSizeDescription);
bw.ReportProgress((int)(((decimal)SentBytes / (decimal)FileSize) * 100), SummaryText);
}
catch (Exception ex)
{
Debug.WriteLine("Exception: " + ex.ToString());
if (NumRetries++ < MaxRetries)
{
fs.Position -= BytesRead;
}
else
{
throw new Exception(String.Format("Error occurred during upload, too many retries. \n{0}", ex.ToString()));
}
}
BytesRead = fs.Read(Buffer, 0, ChunkSize);
}
}
}
using (FtpWebResponse response = (FtpWebResponse)request.GetResponse())
System.Diagnostics.Debug.WriteLine(String.Format("Upload File Complete, status {0}", response.StatusDescription));
}
catch (WebException ex)
{
switch (ex.Status)
{
case WebExceptionStatus.NameResolutionFailure:
ConnectionError = "Error: Please check the ftp address";
break;
case WebExceptionStatus.Timeout:
ConnectionError = "Error: Timout Request";
break;
}
}
}
public static string GetFileSize(long numBytes)
{
string fileSize = "";
if(numBytes > 1073741824)
fileSize = String.Format("{0:0.00} Gb", (double)numBytes / 1073741824);
else if(numBytes > 1048576)
fileSize = String.Format("{0:0.00} Mb", (double)numBytes / 1048576);
else
fileSize = String.Format("{0:0} Kb", (double)numBytes / 1024);
if(fileSize == "0 Kb")
fileSize = "1 Kb";
return fileSize;
}
}
public class FtpSettings
{
public string Host, Username, Password, TargetFolder, SourceFile;
public bool Passive;
public int Port = 21;
}
}
It is a bit long, but I couldn't find a way to narrow the code since it's all connected to each other.
What I need it to do is if I selected more than one file make something like a queue and automatic upload one file when finished upload the next file and so on until the last file.
Today I can upload only one file. Single file each time.
I need that it will automatically upload all the selected files. Using the progressBar and the backgroundworker like it is now.
Here is a procedure how to upload multiple files from the directory where ftp - an address of ftp server:
private void uploadFTP(DirectoryInfo d, string ftp)
{
FileInfo[] flist = d.GetFiles();
if (flist.GetLength(0) > 0)
{
foreach (FileInfo txf in flist)
{
FtpWebRequest request = (FtpWebRequest)FtpWebRequest.Create(ftp + txf.Name);
request.Method = WebRequestMethods.Ftp.UploadFile;
request.Credentials = new NetworkCredential("username", "password");
request.UsePassive = true;
request.UseBinary = true;
request.KeepAlive = false;
FileStream stream = File.OpenRead(txf.FullName);
byte[] buffer = new byte[stream.Length];
stream.Read(buffer, 0, buffer.Length);
stream.Close();
Stream reqStream = request.GetRequestStream();
reqStream.Write(buffer, 0, buffer.Length);
reqStream.Close();
txf.Delete();
}
}
}
You should be using
OpenFileDialog1.FileNames
And iterate on those elements to upload them one by one.
FileNames Property
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.
I am trying to upload an image as an attachment in REST WCF Service and I am getting the following error.
"Access to path "C:\ImageUpload" is denied"
I have enabled Full Contorl permissions to this folder. I dont understand why I am getting this error.
I am new to WCF, and the most of the code I gathered from online resources.
Appreciate if you could let me know If there is any mistake in my code.
Here is my code.
REST WCF Service Code:
[OperationContract]
[WebInvoke(UriTemplate = "uploadImage/{parameter1}")]
void uploadImage(Stream fileStream);
public void uploadImage(Stream fileStream)
{
string filePath = #"C:\ImageUpload";
FileStream filetoUpload = new FileStream(filePath, FileMode.Create);
byte[] byteArray = new byte[10000];
int bytesRead, totalBytesRead = 0;
do
{
bytesRead = fileStream.Read(byteArray, 0, byteArray.Length);
totalBytesRead += bytesRead;
}
while (bytesRead > 0);
filetoUpload.Write(byteArray, 0, byteArray.Length);
filetoUpload.Close();
filetoUpload.Dispose();
}
This is my Test Client Code(Simple .aspx web page)
protected void btnUpload_Click(object sender, EventArgs e)
{
string file = FileUpload1.FileName;
RESTService1Client client = new RESTService1Client();
byte[] bytearray = null;
string name = "";
if (FileUpload1.HasFile)
{
name = FileUpload1.FileName;
Stream stream = FileUpload1.FileContent;
stream.Seek(0, SeekOrigin.Begin);
bytearray = new byte[stream.Length];
int count = 0;
while (count < stream.Length)
{
bytearray[count++] = Convert.ToByte(stream.ReadByte());
}
}
WebClient wclient = new WebClient();
wclient.Headers.Add("Content-Type", "image/jpeg");
client.uploadImage(FileUpload1.FileContent);
}
It's likely nothing to do with WCF or your code. It really is highly probable that permissions on that folder are insufficient for the IIS process user. By default the ASP.NET user is Network Service.
Try creating a new Windows user just for your ASP.NET application. Grant that user explicit read/write access to the upload folder. Then use Impersonation to make ASP.NET use that user.
http://www.codeproject.com/Articles/107940/Back-to-Basic-ASP-NET-Runtime-Impersonation
Rewrite server side as such:
REST WCF Service Code:
[OperationContract]
[WebInvoke(UriTemplate = "uploadImage/{parameter1}/{parameter2}")]
void uploadImage(Stream fileStream, string fileName);
.
public void uploadImage(Stream fileStream, string fileName)
{
string filePath = #"C:\ImageUpload\";
using (FileStream filetoUpload = new FileStream(filePath + fileName, FileMode.Create))
{
byte[] byteArray = new byte[10000];
int bytesRead = 0;
do
{
bytesRead = fileStream.Read(byteArray, 0, byteArray.Length);
if (bytesRead > 0)
{
filetoUpload.Write(byteArray, 0, bytesRead);
}
}
while (bytesRead > 0);
}
}
and your client side as such:
protected void btnUpload_Click(object sender, EventArgs e)
{
if (FileUpload1.HasFile)
{
RESTService1Client client = new RESTService1Client();
client.uploadImage(FileUpload1.FileContent, Path.GetFileName(FileUpload1.FileName));
}
}
I am uploading files to ftp using FtpWebRequest. I need to show the status that how much is done.
So far my code is:
public void Upload(string filename, string url)
{
FileInfo fileInf = new FileInfo(filename);
string uri = "ftp://" + url + "/" + fileInf.Name;
FtpWebRequest reqFTP;
//string uri = "ftp://" + Host + "/public_html/testing/blogtest/" + fileInf.Name;
// Create FtpWebRequest object from the Uri provided
reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(uri));
// Provide the WebPermission Credintials
reqFTP.Credentials = new NetworkCredential(Username, Password);
// By default KeepAlive is true, where the control connection is not closed
// after a command is executed.
reqFTP.KeepAlive = false;
//reqFTP.UsePassive = true;
// 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();
// 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();
}
The easiest is to use BackgroundWorker and put your code into DoWork event handler. And report progress with BackgroundWorker.ReportProgress.
The basic idea:
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
var ftpWebRequest = (FtpWebRequest)WebRequest.Create("ftp://example.com");
ftpWebRequest.Method = WebRequestMethods.Ftp.UploadFile;
using (var inputStream = File.OpenRead(fileName))
using (var outputStream = ftpWebRequest.GetRequestStream())
{
var buffer = new byte[1024 * 1024];
int totalReadBytesCount = 0;
int readBytesCount;
while ((readBytesCount = inputStream.Read(buffer, 0, buffer.Length)) > 0)
{
outputStream.Write(buffer, 0, readBytesCount);
totalReadBytesCount += readBytesCount;
var progress = totalReadBytesCount * 100.0 / inputStream.Length;
backgroundWorker1.ReportProgress((int)progress);
}
}
}
private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
progressBar.Value = e.ProgressPercentage;
}
Make sure WorkerReportsProgress is enabled
backgroundWorker2.WorkerReportsProgress = true;
With BackgroundWorker you can also easily implement upload cancellation.
A trivial example of FTP upload using FtpWebRequest with WinForms progress bar using Task class:
private void button1_Click(object sender, EventArgs e)
{
// Run Upload on background thread
Task.Run(() => Upload());
}
private void Upload()
{
string url = "ftp://ftp.example.com/remote/path/file.zip";
FtpWebRequest request = (FtpWebRequest)WebRequest.Create(url);
request.Credentials = new NetworkCredential("username", "password");
request.Method = WebRequestMethods.Ftp.UploadFile;
using (Stream fileStream = File.OpenRead(#"C:\local\path\file.zip"))
using (Stream ftpStream = request.GetRequestStream())
{
progressBar1.Invoke(
(MethodInvoker)delegate {
progressBar1.Maximum = (int)fileStream.Length; });
byte[] buffer = new byte[10240];
int read;
while ((read = fileStream.Read(buffer, 0, buffer.Length)) > 0)
{
ftpStream.Write(buffer, 0, read);
progressBar1.Invoke(
(MethodInvoker)delegate {
progressBar1.Value = (int)fileStream.Position; });
}
}
}
The core upload code is based on:
Upload and download a file to/from FTP server in C#/.NET
A cancellable approach using the async/await pattern's IProgress interface, taking advantage of overlapped I/O if available. Refer to KB156932 to determine if your scenario qualifies. The cancellation token is checked before opening the streams, but otherwise is offloaded to the streams' async methods while the file is being transferred.
I have done very little benchmarking, but suspect this is only practical when sending large files. The performance of using overlapped I/O may degrade with smaller files and especially smaller buffer sizes.
public async Task FtpAsync(string sourceFile, Uri destinationUri, string user, SecureString password, IProgress<decimal> progress, CancellationToken token)
{
const int bufferSize = 128 * 1024; // 128kb buffer
progress.Report(0m);
var request = (FtpWebRequest)WebRequest.Create(destinationUri);
request.Method = WebRequestMethods.Ftp.UploadFile;
request.Credentials = new NetworkCredential(user, password);
token.ThrowIfCancellationRequested();
using (var fileStream = new FileStream(sourceFile, FileMode.Open, FileAccess.Read, FileShare.Read, bufferSize, true))
{
using (var ftpStream = await request.GetRequestStreamAsync())
{
var buffer = new byte[bufferSize];
int read;
while ((read = await fileStream.ReadAsync(buffer, 0, buffer.Length, token)) > 0)
{
await ftpStream.WriteAsync(buffer, 0, read, token);
var percent = 100m * ((decimal)fileStream.Position / fileStream.Length);
progress.Report(percent);
}
}
}
var response = (FtpWebResponse)await request.GetResponseAsync();
var success = (int)response.StatusCode >= 200 && (int)response.StatusCode < 300;
response.Close();
if (!success)
throw new Exception(response.StatusDescription);
}
See BackgroundWorker, it allows you to run a time consuming task while the GUI still is responsive and also provides progress/cancellation.
First time poster, long-time reader. I have a really annoying problem thats been getting on my nerves. Ive got a program set up so I listen for new files on an FTP server, if theres a new file I download it. From there I work on some of the information in the file, etc. My problem comes when I run through my sequence the second time. That is, on the first file I download everything is totally fine, but as soon as a new file gets detected and my program tries downloading it, my program just hangs.
private static void DownloadFile(string s)
{
try
{
FtpWebRequest request = (FtpWebRequest)WebRequest.Create("ftp://blabla.com/"+s);
request.Method = WebRequestMethods.Ftp.DownloadFile;
request.Credentials = new NetworkCredential("xxx" ,"zzz");
using (FtpWebResponse partResponse = (FtpWebResponse)request.GetResponse())
{
Stream partReader = partResponse.GetResponseStream();
byte[] buffer = new byte[1024];
FileInfo fi = new FileInfo(path);
FileStream memStream = fi.Create();
while (true)
{
int bytesRead = partReader.Read(buffer, 0, buffer.Length - 1);
if (bytesRead == 0)
break;
memStream.Write(buffer, 0, bytesRead);
}
partResponse.Close();
memStream.Close();
}
Console.WriteLine(DateTime.Now + " file downloaded");
MoveFileToInProgress(s);
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
}
The line it hangs on is this one:
using (FtpWebResponse partResponse = (FtpWebResponse)request.GetResponse())
The reason my method here is static is because Im just running it in a different project to test it.. My question here is, how come it only ever dies on the second file? Ive been staring myself blind for hours now!
I ran into this problem as well... try finishing your request first and then closing it before trying to retrieve the response. That worked for me (actually tried it after reading comment by MartinNielsen). Here is what I did.
// connect to the ftp site
FtpWebRequest ftpRequest = (FtpWebRequest)WebRequest.Create(ftpUri);
ftpRequest.Method = WebRequestMethods.Ftp.UploadFile;
ftpRequest.Credentials = new NetworkCredential(ftpUser, ftpPassword);
// setting proxy to null so that it does not go through the proxy
ftpRequest.Proxy = null;
// get file information
StreamReader fileStream = new StreamReader(filePath);
byte[] fileBytes = Encoding.UTF8.GetBytes(fileStream.ReadToEnd());
ftpRequest.ContentLength = fileBytes.Length;
fileStream.Close();
// open connection to ftp site
Stream ftpRequestStream = ftpRequest.GetRequestStream();
// write the file to the stream
ftpRequestStream.Write(fileBytes, 0, fileBytes.Length);
// close the stream
ftpRequestStream.Close();
// get the response from the server
FtpWebResponse ftpUploadResponse = (FtpWebResponse)ftpRequest.GetResponse();
string result = ftpUploadResponse.StatusDescription;
// close response
ftpUploadResponse.Close();
// return response to calling code
return result;
Here are a couple of the resources that I used when writing this code (won't let me post more than 2, there were more)
How to: Upload Files with FTP
Uploading a file -- "The requested URI is invalid for this FTP command"
I'm not expert on C# but I use this code to download files from my ftp:
public void Download(string filename)
{
// I try to download five times before crash
for (int i = 1; i < 5; i++)
{
try
{
FtpWebRequest ftp = (FtpWebRequest)FtpWebRequest.Create(Global.Path + "/" + filename);
ftp.Credentials = new NetworkCredential(User, Pass);
ftp.KeepAlive = false;
ftp.Method = WebRequestMethods.Ftp.DownloadFile;
ftp.UseBinary = true;
ftp.Proxy = null;
int buffLength = 2048;
byte[] buff = new byte[buffLength];
int contentLen;
string LocalDirectory = Application.StartupPath.ToString() + "/downloads/" + filename;
using (FileStream fs = new FileStream(LocalDirectory, FileMode.Create, FileAccess.Write, FileShare.None))
using (Stream strm = ftp.GetResponse().GetResponseStream())
{
contentLen = strm.Read(buff, 0, buffLength);
while (contentLen != 0)
{
fs.Write(buff, 0, contentLen);
contentLen = strm.Read(buff, 0, buffLength);
}
}
Process.Start(LocalDirectory);
break;
}
catch (Exception exc)
{
if (i == 5)
{
MessageBox.Show("Can't download, try number: " + i + "/5 \n\n Error: " + exc.Message,
"Problem downloading the file");
}
}
}
}
Tell me if it works for you :)