hi people I'm trying to put a download progress bar to my ftp download program it kinda works but progress bar is not filling with the download or after download but i get the download completed message the code is below ;
public void yap(object o)
{
(o as Label).Text = "DOWNLOADING";
}
private void button1_Click(object sender, EventArgs e)
{
CheckForIllegalCrossThreadCalls = false;
ParameterizedThreadStart p = new ParameterizedThreadStart(yap);
Thread t = new Thread(p);
t.Start(label2);
BackgroundWorker _backgroundWorker = new BackgroundWorker();
_backgroundWorker.DoWork += _backgroundWorker_DoWork;
_backgroundWorker.WorkerReportsProgress = true;
_backgroundWorker.ProgressChanged +=
new ProgressChangedEventHandler(_backgroundWorker_ProgressChanged);
_backgroundWorker.RunWorkerCompleted +=
new RunWorkerCompletedEventHandler(_backgroundWorker_RunWorkerCompleted);
_backgroundWorker.RunWorkerAsync();
}
void _backgroundWorker_RunWorkerCompleted
(object sender, RunWorkerCompletedEventArgs e)
{
MessageBox.Show("Download Completed");
}
void _backgroundWorker_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
progressBar1.Value = e.ProgressPercentage;
}
private void Form1_Load(object sender, EventArgs e)
{
AutoSizeMode = AutoSizeMode.GrowAndShrink;
progressBar1.Maximum = 100;
}
void _backgroundWorker_DoWork(object sender, DoWorkEventArgs e)
{
Dispatcher.CurrentDispatcher.Invoke
(System.Windows.Threading.DispatcherPriority.Background,new Action(delegate()
{
string yol = Environment.CurrentDirectory;
FtpWebRequest FTP;
try
{
FileStream SR = new FileStream(yol + "\\list.gz", FileMode.Create);
FTP = (FtpWebRequest)FtpWebRequest.Create(new Uri
("ftp://" + textBox1.Text + "/" + "/usr/valapp/etc/list.gz"));
FTP.Credentials = new NetworkCredential("username", "password");
FTP.Method = WebRequestMethods.Ftp.DownloadFile;
FTP.UseBinary = true;
FtpWebResponse response = (FtpWebResponse)FTP.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)
{
SR.Write(buffer, 0, readCount);
readCount = ftpStream.Read(buffer, 0, bufferSize);
}
ftpStream.Close();
SR.Close();
response.Close();
MessageBox.Show("File Downloaded!");
for (int i = 0; i <= 100; i++)
{
backgroundWorker1.ReportProgress(i);
System.Threading.Thread.Sleep(20);
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Error");
}
}));
}
}
}
Code might be look complex but its totally works as i told only progress bar is not filling thank you.
int cnt=0;
double totalentry=response.ContentLength/bufferSize;
while (readCount > 0)
{
SR.Write(buffer, 0, readCount);
readCount = ftpStream.Read(buffer, 0, bufferSize);
if(_backgroundWorker.WorkerReportsProgress)
{
_backgroundWorker.ReportProgress(cnt++*100/(int)totalentry);
}
}
You may just edit this part of the code.
Related
Is it possible to separate input and output threads with Naudio and AsioOut?
I want to send input and output data over udp protocol and play it.
Now i'm doing it like that -->
private void DefaultConfiguration()
{
var channelCount = _asioOut.DriverInputChannelCount;
var waveFormat = new WaveFormat(SampleRate, 2);
_bufferedWaveProvider = new BufferedWaveProvider(waveFormat) { ReadFully = false };
_asioOut.InitRecordAndPlayback(_bufferedWaveProvider, 2, SampleRate);
_asioOut.DriverResetRequest += OnAsioOutDriverResetRequest;
_asioOut.AudioAvailable += OnUdpAsioOutAudioAvailable;
}
private async void OnUdpAsioOutAudioAvailable(object sender, AsioAudioAvailableEventArgs e)
{
int fullBufferSize = e.SamplesPerBuffer * 4;
byte[] send = new byte[fullBufferSize];
CopyBytes(e.InputBuffers[0], send, 0, fullBufferSize);
await _udpConsumer.SendToAsync(send, SocketFlags.None, _endpoint);
byte[] buffer = new byte[2048];
await _udpConsumer.ReceiveAsync(buffer, SocketFlags.None);
CopyBytes(buffer, e.OutputBuffers[0], 0, 2048);
CopyBytes(buffer, e.OutputBuffers[1], 0, 2048);
e.WrittenToOutputBuffers = true;
}
but i want separate input and output to reduce latency.
Also i tried to do that in this way, but it don't actually help.
private void DefaultConfiguration()
{
var channelCount = _asioOut.DriverInputChannelCount;
var waveFormat = new WaveFormat(SampleRate, 2);
_bufferedWaveProvider = new BufferedWaveProvider(waveFormat) { ReadFully = false };
_asioOut.InitRecordAndPlayback(_bufferedWaveProvider, 2, SampleRate);
_asioOut.DriverResetRequest += OnAsioOutDriverResetRequest;
_asioOut.AudioAvailable += OnUdpAsioOutAudioAvailableInput;
_asioOut.AudioAvailable += OnUdpAsioOutAudioAvailableOutput;
}
private async void OnUdpAsioOutAudioAvailableInput(object sender, AsioAudioAvailableEventArgs e)
{
int fullBufferSize = e.SamplesPerBuffer * 4;
byte[] send = new byte[fullBufferSize];
CopyBytes(e.InputBuffers[0], send, 0, fullBufferSize);
await _udpConsumer.SendToAsync(send, SocketFlags.None, _endpoint);
e.WrittenToOutputBuffers = true;
}
private async void OnUdpAsioOutAudioAvailableOutput(object sender, AsioAudioAvailableEventArgs e)
{
byte[] buffer = new byte[2048];
await _udpConsumer.ReceiveAsync(buffer, SocketFlags.None);
CopyBytes(buffer, e.OutputBuffers[0], 0, 2048);
CopyBytes(buffer, e.OutputBuffers[1], 0, 2048);
e.WrittenToOutputBuffers = true;
}
How can I upload a PDF file to host via C# so that it is available for download via an adroid app? This is what I have tried, but it does not work. What am I doing wrong?
static void backgroundWorker_DoWork(object sender, DoWorkEventArgs e)
{
string fileName = ((FTPsetting)e.Argument).Filename;
string fullName = ((FTPsetting)e.Argument).FullName;
string username = ((FTPsetting)e.Argument).Username;
string password = ((FTPsetting)e.Argument).Password;
string server = ((FTPsetting)e.Argument).Server;
FtpWebRequest request = (FtpWebRequest)WebRequest.Create(new Uri(string.Format("{0}/{1}", server, fileName)));
request.Method = WebRequestMethods.Ftp.UploadFile;
request.Credentials = new NetworkCredential(username, password);
Stream ftpstream = request.GetRequestStream();
FileStream fs = File.OpenRead(fullName);
byte[] buffer = new byte[1024];
double total = (double)fs.Length;
int byteread = 0;
double read = 0;
do
{
if (!backgroundWorker.CancellationPending)
{
byteread = fs.Read(buffer, 0, 1024);
ftpstream.Write(buffer, 0, byteread);
read += (double)byteread;
double percontage = read / total * 100;
backgroundWorker.ReportProgress((int)percontage);
}
}
while (byteread != 0);
fs.Close();
ftpstream.Close();
}
static void backgroundWorker_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
Console.WriteLine("Completed" + e.ProgressPercentage + "%");
}
This is the method:
Getting the Length of the files give 0 already.
public void DownloadFtpContent(object sender ,string file, string filesdirectories,string fn)
{
try
{
BackgroundWorker bw = sender as BackgroundWorker;
string filenameonly = Path.GetFileName(file);
string ftpdirectories = Path.Combine(ftpcontentdir, filesdirectories);
string fileurl = "ftp://" + file;
FtpWebRequest reqFTP;
reqFTP = (FtpWebRequest)FtpWebRequest.Create(fileurl);
reqFTP.Credentials = new NetworkCredential(UserName, Password);
reqFTP.UseBinary = true;
reqFTP.UsePassive = true;
reqFTP.KeepAlive = true;
reqFTP.Method = WebRequestMethods.Ftp.DownloadFile;
reqFTP.Proxy = null;
FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();
Stream responseStream = response.GetResponseStream();
if (!Directory.Exists(ftpdirectories))
{
Directory.CreateDirectory(ftpdirectories);
}
FileStream writeStream = new FileStream(ftpdirectories + "\\" + filenameonly, FileMode.Create);
string fnn = ftpdirectories + "\\" + filenameonly;
int Length = 2048;
Byte[] buffer = new Byte[Length];
int bytesRead = responseStream.Read(buffer, 0, Length);
long FileSize = new FileInfo(fnn).Length;
string FileSizeDescription = GetFileSize(FileSize);
while (bytesRead > 0)
{
writeStream.Write(buffer, 0, bytesRead);
bytesRead = responseStream.Read(buffer, 0, Length);
string SummaryText = String.Format("Transferred {0} / {1}", GetFileSize(bytesRead), FileSizeDescription);
bw.ReportProgress((int)(((decimal)bytesRead / (decimal)FileSize) * 100), SummaryText);
}
writeStream.Close();
response.Close();
}
catch (WebException wEx)
{
//MessageBox.Show(wEx.Message, "Download Error");
}
catch (Exception ex)
{
//MessageBox.Show(ex.Message, "Download Error");
}
}
}
Already on this line the result is 0:
long FileSize = new FileInfo(fnn).Length;
In fnn i have: c:\myftpdownloads\root\Images\CB 967x330.jpg
Why the result of the Length is 0 ?
And the file is not 0kb size.
EDIT
This is how i'm calling the download method from backgroundworker dowork event:
private void backgroundWorker2_DoWork(object sender, DoWorkEventArgs e)
{
for (int i = 0; i < numberOfFiles.Count; i++)
{
int fn = numberOfFiles[i].IndexOf(txtHost.Text, 0);
string fn1 = numberOfFiles[i].Substring(txtHost.Text.Length + 1, numberOfFiles[i].Length - (txtHost.Text.Length + 1));
string dirs = Path.GetDirectoryName(fn1);
string filename = Path.GetFileName(fn1);
ftpProgress1.DownloadFtpContent(sender,numberOfFiles[i], dirs, filename);
}
}
In fnn i have: c:\myftpdownloads\root\Images\CB 967x330.jpg Why the result of the Length is 0 ?
It doesn't really matter why the result of the length is 0. It does matter that you divide that number by 0 without any protection.
Just check before you divide:
if( FileSize != 0 ){...}
I'm going in circles searching and reading forums on how to solve this problems. After a day of trying I'm still at a loss how to solve my problem. I'm uploading a file and need to return the % in a a textbox. I'm having no problem with the upload portion and have no problems returning the values using the BackgroundWorker if I include all my code within the same class. However, what I'm doing is calling an ftp class from form1. I need the ftp class to return the percentage to form1 so I can can display in my UI and also need to have the server response codes returned from my ftp class to display in my form1. Everything was working ok before I tried to run this in a BackgroundWorker process, with the exception of course that the UI becomes unresponsive and returns all status messages after upload completed. Heres my code as it stands now. How do I get the percentage from ftp class and pass it back to form1, as well as the server response code once completed?
public partial class Form1 : Form
{
private BackgroundWorker bw = new BackgroundWorker();
private string ftpServer = #"ftp://10.0.0.0";
private string ftpUser = #"user";
private string ftpPass = #"pass";
private string ftpRemoteFile = #"myfile.exe";
private string ftpLocalFile = #"C:\Uploads\file.exe";
public Form1()
{
InitializeComponent();
bw.WorkerReportsProgress = true;
bw.DoWork += new DoWorkEventHandler(bw_DoWork);
bw.ProgressChanged += new ProgressChangedEventHandler(bw_ProgressChanged);
bw.RunWorkerCompleted += new RunWorkerCompletedEventHandler(bw_RunWorkerCompleted);
}
private void sendButton_Click(object sender, EventArgs e)
{
progressRichTextBox.Text = "Sending";
if (bw.IsBusy != true)
{
bw.RunWorkerAsync();
}
}
private void bw_DoWork(object sender, DoWorkEventArgs e)
{
BackgroundWorker worker = sender as BackgroundWorker;
ftp ftpClient = new ftp(ftpServer, ftpUser, ftpPass);
ftpClient.upload(progressRichTextBox, ftpRemoteFile, ftpLocalFile);
}
private void bw_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
if (!(e.Error == null))
{
this.progressRichTextBox.Text = ("Error: " + e.Error.Message);
}
else
{
this.progressRichTextBox.Text = "Done!";
}
}
private void bw_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
this.progressRichTextBox.Text = (e.ProgressPercentage.ToString() + "%");
}
}
And heres the ftp class:
public void upload(System.Windows.Forms.RichTextBox progressRichTextBox, string remoteFile, string localFile)
{
FileInfo fileInfo = new FileInfo(localFile);
/* Create an FTP Request */
ftpRequest = (FtpWebRequest)FtpWebRequest.Create(host + "/" + remoteFile);
/* Log in to the FTP Server with the User Name and Password Provided */
ftpRequest.Credentials = new NetworkCredential(user, pass);
/* Specify generic group name for faster upload */
ftpRequest.ConnectionGroupName = "AffiliateUpload";
/* Specify the Type of FTP Request */
ftpRequest.Method = WebRequestMethods.Ftp.UploadFile;
/* Server connection options */
ftpRequest.UseBinary = true;
ftpRequest.UsePassive = true;
ftpRequest.KeepAlive = true;
ftpRequest.ContentLength = fileInfo.Length;
/* Buffer for the Data */
byte[] buff = new byte[bufferSize];
int contentLen;
/* Open a File Stream to Read the File for Upload */
FileStream localFileStream = fileInfo.OpenRead();
try
{
// Stream to which the file to be upload is written
ftpStream = ftpRequest.GetRequestStream();
// Read from the file stream 2kb at a time
contentLen = localFileStream.Read(buff, 0, bufferSize);
// Till Stream content ends
while (contentLen != 0)
{
// Write Content from the file stream to the
// FTP Upload Stream
ftpStream.Write(buff, 0, contentLen);
contentLen = localFileStream.Read(buff, 0, bufferSize);
}
// Close the file stream and the Request Stream
ftpStream.Close();
localFileStream.Close();
ftpRequest = null;
}
catch (Exception ex)
{
Console.WriteLine("Failed sending to " + host + "/" + remoteFile + " (" + ex.Message + ")");
}
}
You don't need to update progressRichTextBox in your upload method. Remove that parameter. You need to provide the worker object to your upload method and call worker.ReportProgress on it.
Please Help! I've tried everything, i dont know what else to do. I just want to upload an image that the user chooses from their library to my websever.
I already have a code that uses webclient to upload to a url.
private void OnChoosePicturel(object sender, RoutedEventArgs e)
{
PhotoChooserTask task = new PhotoChooserTask();
task.Completed += task_Completed;
task.Show();
}
private void task_Completed(object sender, PhotoResult e)
{
if (e.TaskResult != TaskResult.OK)
return;
const int BLOCK_SIZE = 4096;
Uri uri = new Uri("URL");
WebClient wc = new WebClient();
NetworkCredential g = new NetworkCredential();
g.UserName = "USERNAME";
g.Password = "PASSWORD";
wc.Credentials = g;
wc.AllowReadStreamBuffering = true;
wc.AllowWriteStreamBuffering = true;
try
{
// what to do when write stream is open
wc.OpenWriteCompleted += (s, args) =>
{
using (BinaryReader br = new BinaryReader(e.ChosenPhoto))
{
using (BinaryWriter bw = new BinaryWriter(args.Result))
{
long bCount = 0;
long fileSize = e.ChosenPhoto.Length;
byte[] bytes = new byte[BLOCK_SIZE];
do
{
bytes = br.ReadBytes(BLOCK_SIZE);
bCount += bytes.Length;
bw.Write(bytes);
} while (bCount < fileSize);
}
}
};
}
catch(Exception t)
{
}
// what to do when writing is complete
wc.WriteStreamClosed += (s, args) =>
{
MessageBox.Show("Send Complete");
};
// Write to the WebClient
wc.OpenWriteAsync(uri, "STOR");
}
The problem is , the webclient class only works for "http" urls, but i need to connect and upload the file to an "ftp" url. How do i do this? Ive tried EVERYTHING. Nothing works.