Guys this the code to store file on ftp. Can any one reconfigure this code so that it stores the contents of the richtextbox in windows forms I'm writing anything on richtextbox when I click button it should store directly ftp.
{
Stream requestStream = null;
FileStream fileStream = null;
FtpWebResponse uploadResponse = null;
try
{
uploadUrl = "ftp://ftp.personalwebars.com/ATM/";
fileName = txtTitle.Text + ".txt";
FtpWebRequest uploadRequest = (FtpWebRequest)WebRequest.Create(uploadUrl + #"/" + fileName);
uploadRequest.Method = WebRequestMethods.Ftp.UploadFile;
//Since the FTP you are downloading to is secure, send
//in user name and password to be able upload the file
ICredentials credentials = new NetworkCredential(user, pswd);
uploadRequest.Credentials = credentials;
//UploadFile is not supported through an Http proxy
//so we disable the proxy for this request.
uploadRequest.Proxy = null;
//uploadRequest.UsePassive = false; <--found from another forum and did not make a difference
requestStream = uploadRequest.GetRequestStream();
byte[] buffer = new byte[1024];
int bytesRead;
while (true)
{
bytesRead = fileStream.Read(buffer, 0, buffer.Length);
if (bytesRead == 0)
break;
requestStream.Write(buffer, 0, bytesRead);
}
//The request stream must be closed before getting
//the response.
requestStream.Close();
uploadResponse =
(FtpWebResponse)uploadRequest.GetResponse();
lblAuthentication.Text = "Your solution has been submitted in txt Mode. Thank You";
}
catch (WebException ex)
{
}
finally
{
if (uploadResponse != null)
uploadResponse.Close();
if (fileStream != null)
fileStream.Close();
if (requestStream != null)
requestStream.Close();
}
}
Try this, extract the string from the text box and pass it in as the content parameter,
public void Send(string url, string fileName, string content, string user, string password)
{
byte[] bytes = Encoding.ASCII.GetBytes(content)
var request = (FtpWebRequest) WebRequest.Create(new Uri(url + #"/" + fileName));
request.Method = WebRequestMethods.Ftp.UploadFile;
request.UsePassive = false;
request.Credentials = new NetworkCredential(user, password);
request.ContentLength = bytes.Length;
var requestStream = request.GetRequestStream();
requestStream.Write(bytes, 0, bytes.Length);
requestStream.Close();
var response = (FtpWebResponse) request.GetResponse();
if (response != null) response.Close();
}
Related
I want to download file from FTP and open a download/save prompt in user's web browser, when the user clicks on a download button on ASP.NET C# page.
string strDownloadURL = System.Configuration.ConfigurationSettings.AppSettings["DownloadURL"];
string HostName = System.Configuration.ConfigurationSettings.AppSettings["HostName"];
string strUser = System.Configuration.ConfigurationSettings.AppSettings["BasicAuthenticationUser"];
string strPWD = System.Configuration.ConfigurationSettings.AppSettings["BasicAuthenticationPWD"];
FtpWebRequest request = (FtpWebRequest)WebRequest.Create(HostName + strFile);
request.Method = WebRequestMethods.Ftp.DownloadFile;
request.Credentials = new NetworkCredential(strUser, strPWD);
request.UsePassive = true;
request.UseBinary = true;
request.KeepAlive = false;
FtpWebResponse response = (FtpWebResponse)request.GetResponse();
Stream responseStream = response.GetResponseStream();
string fileName = #"c:\temp\" + strFile + "";
Directory.CreateDirectory(Path.GetDirectoryName(fileName));
FileStream file = File.Create(fileName);
byte[] buffer = new byte[2 * 1024];
int read;
while ((read = responseStream.Read(buffer, 0, buffer.Length)) > 0) { file.Write(buffer, 0, read); }
file.Close();
responseStream.Close();
response.Close();
So, assuming you're writing the FTP request's response stream down to the ASP.NET response stream, and want to trigger the download dialog in the browser, you'll want to set the Content-Disposition header in the response.
// note: since you are writing directly to client, I removed the `file` stream
// in your original code since we don't need to store the file locally...
// or so I am assuming
Response.AddHeader("content-disposition", "attachment;filename=" + strFile);
byte[] buffer = new byte[2 * 1024];
int read;
while ((read = responseStream.Read(buffer, 0, buffer.Length)) > 0)
{
Response.OutputStream.Write(buffer, 0, read);
}
responseStream.Close();
response.Close();
The answer by #moribvndvs is correct. But the code can be way simpler with use of WebClient.OpenRead and Stream.CopyTo:
var filename = "file.zip";
Response.AddHeader("Content-Disposition", "attachment; filename=" + filename);
var client = new WebClient();
client.Credentials = new NetworkCredential("username", "password");
var url = "ftp://ftp.example.com/remote/path/" + filename;
using (var ftpStream = client.OpenRead(url))
{
ftpStream.CopyTo(Response.OutputStream);
}
(where Response is ASP.NET HttpResponse).
See also Upload and download a file to/from FTP server in C#/.NET.
I try upload a file to an FTP-server with C#. The file is uploaded but with zero bytes.
private void button2_Click(object sender, EventArgs e)
{
var dirPath = #"C:/Documents and Settings/sander.GD/Bureaublad/test/";
ftp ftpClient = new ftp("ftp://example.com/", "username", "password");
string[] files = Directory.GetFiles(dirPath,"*.*");
var uploadPath = "/httpdocs/album";
foreach (string file in files)
{
ftpClient.createDirectory("/test");
ftpClient.upload(uploadPath + "/" + Path.GetFileName(file), file);
}
if (string.IsNullOrEmpty(txtnaam.Text))
{
MessageBox.Show("Gelieve uw naam in te geven !");
}
}
The existing answers are valid, but why re-invent the wheel and bother with lower level WebRequest types while WebClient already implements FTP uploading neatly:
using (var client = new WebClient())
{
client.Credentials = new NetworkCredential(ftpUsername, ftpPassword);
client.UploadFile("ftp://host/path.zip", WebRequestMethods.Ftp.UploadFile, localFile);
}
Easiest way
The most trivial way to upload a file to an FTP server using .NET framework is using WebClient.UploadFile method:
WebClient client = new WebClient();
client.Credentials = new NetworkCredential("username", "password");
var url = "ftp://ftp.example.com/remote/path/file.zip";
client.UploadFile(url, #"C:\local\path\file.zip");
Advanced options
If you need a greater control, that WebClient does not offer (like TLS/SSL encryption, ascii/text transfer mode, active mode, transfer resuming, progress monitoring, etc), use FtpWebRequest. Easy way is to just copy a FileStream to an FTP stream using Stream.CopyTo:
var 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())
{
fileStream.CopyTo(ftpStream);
}
Progress monitoring
If you need to monitor an upload progress, you have to copy the contents by chunks yourself:
var 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())
{
byte[] buffer = new byte[10240];
int read;
while ((read = fileStream.Read(buffer, 0, buffer.Length)) > 0)
{
ftpStream.Write(buffer, 0, read);
Console.WriteLine("Uploaded {0} bytes", fileStream.Position);
}
}
For GUI progress (WinForms ProgressBar), see C# example at:
How can we show progress bar for upload with FtpWebRequest
Uploading folder
If you want to upload all files from a folder, see
Upload directory of files to FTP server using WebClient.
For a recursive upload, see
Recursive upload to FTP server in C#
.NET 5 Guide
async Task<FtpStatusCode> FtpFileUploadAsync(string ftpUrl, string userName, string password, string filePath)
{
FtpWebRequest request = (FtpWebRequest)WebRequest.Create(ftpUrl);
request.Method = WebRequestMethods.Ftp.UploadFile;
request.Credentials = new NetworkCredential(userName, password);
using (FileStream fileStream = new FileStream(filePath, FileMode.Open, FileAccess.Read))
using (Stream requestStream = request.GetRequestStream())
{
await fileStream.CopyToAsync(requestStream);
}
using (FtpWebResponse response = (FtpWebResponse)await request.GetResponseAsync())
{
return response.StatusCode;
}
}
.NET Framework
public void UploadFtpFile(string folderName, string fileName)
{
FtpWebRequest request;
string folderName;
string fileName;
string absoluteFileName = Path.GetFileName(fileName);
request = WebRequest.Create(new Uri(string.Format(#"ftp://{0}/{1}/{2}", "127.0.0.1", folderName, absoluteFileName))) as FtpWebRequest;
request.Method = WebRequestMethods.Ftp.UploadFile;
request.UseBinary = 1;
request.UsePassive = 1;
request.KeepAlive = 1;
request.Credentials = new NetworkCredential(user, pass);
request.ConnectionGroupName = "group";
using (FileStream fs = File.OpenRead(fileName))
{
byte[] buffer = new byte[fs.Length];
fs.Read(buffer, 0, buffer.Length);
fs.Close();
Stream requestStream = request.GetRequestStream();
requestStream.Write(buffer, 0, buffer.Length);
requestStream.Flush();
requestStream.Close();
}
}
How to use
UploadFtpFile("testFolder", "E:\\filesToUpload\\test.img");
use this in your foreach
and you only need to create folder one time
to create a folder
request = WebRequest.Create(new Uri(string.Format(#"ftp://{0}/{1}/", "127.0.0.1", "testFolder"))) as FtpWebRequest;
request.Method = WebRequestMethods.Ftp.MakeDirectory;
FtpWebResponse ftpResponse = (FtpWebResponse)request.GetResponse();
The following works for me:
public virtual void Send(string fileName, byte[] file)
{
ByteArrayToFile(fileName, file);
var request = (FtpWebRequest) WebRequest.Create(new Uri(ServerUrl + fileName));
request.Method = WebRequestMethods.Ftp.UploadFile;
request.UsePassive = false;
request.Credentials = new NetworkCredential(UserName, Password);
request.ContentLength = file.Length;
var requestStream = request.GetRequestStream();
requestStream.Write(file, 0, file.Length);
requestStream.Close();
var response = (FtpWebResponse) request.GetResponse();
if (response != null)
response.Close();
}
You can't read send the file parameter in your code as it is only the filename.
Use the following:
byte[] bytes = File.ReadAllBytes(dir + file);
To get the file so you can pass it to the Send method.
public static void UploadFileToFtp(string url, string filePath, string username, string password)
{
var fileName = Path.GetFileName(filePath);
var request = (FtpWebRequest)WebRequest.Create(url + fileName);
request.Method = WebRequestMethods.Ftp.UploadFile;
request.Credentials = new NetworkCredential(username, password);
request.UsePassive = true;
request.UseBinary = true;
request.KeepAlive = false;
using (var fileStream = File.OpenRead(filePath))
{
using (var requestStream = request.GetRequestStream())
{
fileStream.CopyTo(requestStream);
requestStream.Close();
}
}
var response = (FtpWebResponse)request.GetResponse();
Console.WriteLine("Upload done: {0}", response.StatusDescription);
response.Close();
}
In the first example must change those to:
requestStream.Flush();
requestStream.Close();
First flush and after that close.
This works for me,this method will SFTP a file to a location within your network.
It uses SSH.NET.2013.4.7 library.One can just download it for free.
//Secure FTP
public void SecureFTPUploadFile(string destinationHost,int port,string username,string password,string source,string destination)
{
ConnectionInfo ConnNfo = new ConnectionInfo(destinationHost, port, username, new PasswordAuthenticationMethod(username, password));
var temp = destination.Split('/');
string destinationFileName = temp[temp.Count() - 1];
string parentDirectory = destination.Remove(destination.Length - (destinationFileName.Length + 1), destinationFileName.Length + 1);
using (var sshclient = new SshClient(ConnNfo))
{
sshclient.Connect();
using (var cmd = sshclient.CreateCommand("mkdir -p " + parentDirectory + " && chmod +rw " + parentDirectory))
{
cmd.Execute();
}
sshclient.Disconnect();
}
using (var sftp = new SftpClient(ConnNfo))
{
sftp.Connect();
sftp.ChangeDirectory(parentDirectory);
using (var uplfileStream = System.IO.File.OpenRead(source))
{
sftp.UploadFile(uplfileStream, destinationFileName, true);
}
sftp.Disconnect();
}
}
publish date: 06/26/2018
https://learn.microsoft.com/en-us/dotnet/framework/network-programming/how-to-upload-files-with-ftp
using System;
using System.IO;
using System.Net;
using System.Text;
namespace Examples.System.Net
{
public class WebRequestGetExample
{
public static void Main ()
{
// Get the object used to communicate with the server.
FtpWebRequest request =
(FtpWebRequest)WebRequest.Create("ftp://www.contoso.com/test.htm");
request.Method = WebRequestMethods.Ftp.UploadFile;
// This example assumes the FTP site uses anonymous logon.
request.Credentials = new NetworkCredential("anonymous",
"janeDoe#contoso.com");
// Copy the contents of the file to the request stream.
byte[] fileContents;
using (StreamReader sourceStream = new StreamReader("testfile.txt"))
{
fileContents = Encoding.UTF8.GetBytes(sourceStream.ReadToEnd());
}
request.ContentLength = fileContents.Length;
using (Stream requestStream = request.GetRequestStream())
{
requestStream.Write(fileContents, 0, fileContents.Length);
}
using (FtpWebResponse response = (FtpWebResponse)request.GetResponse())
{
Console.WriteLine($"Upload File Complete, status
{response.StatusDescription}");
}
}
}
}
Best way I've found is FluentFtp
You can find the repo here:
https://github.com/robinrodricks/FluentFTP
and the quickstart example here:
https://github.com/robinrodricks/FluentFTP/wiki/Quick-Start-Example.
And actually the WebRequest class recommended by a few people here, is not recommended by Microsoft anymore, check out this page:
https://learn.microsoft.com/en-us/dotnet/api/system.net.webrequest?view=net-5.0
// create an FTP client and specify the host, username and password
// (delete the credentials to use the "anonymous" account)
FtpClient client = new FtpClient("123.123.123.123", "david", "pass123");
// connect to the server and automatically detect working FTP settings
client.AutoConnect();
// upload a file and retry 3 times before giving up
client.RetryAttempts = 3;
client.UploadFile(#"C:\MyVideo.mp4", "/htdocs/big.txt",
FtpRemoteExists.Overwrite, false, FtpVerify.Retry);
// disconnect! good bye!
client.Disconnect();
I have observed that -
FtpwebRequest is missing.
As the target is FTP, so the NetworkCredential required.
I have prepared a method that works like this, you can replace the value of the variable ftpurl with the parameter TargetDestinationPath. I had tested this method on winforms application :
private void UploadProfileImage(string TargetFileName, string TargetDestinationPath, string FiletoUpload)
{
//Get the Image Destination path
string imageName = TargetFileName; //you can comment this
string imgPath = TargetDestinationPath;
string ftpurl = "ftp://downloads.abc.com/downloads.abc.com/MobileApps/SystemImages/ProfileImages/" + imgPath;
string ftpusername = krayknot_DAL.clsGlobal.FTPUsername;
string ftppassword = krayknot_DAL.clsGlobal.FTPPassword;
string fileurl = FiletoUpload;
FtpWebRequest ftpClient = (FtpWebRequest)FtpWebRequest.Create(ftpurl);
ftpClient.Credentials = new System.Net.NetworkCredential(ftpusername, ftppassword);
ftpClient.Method = System.Net.WebRequestMethods.Ftp.UploadFile;
ftpClient.UseBinary = true;
ftpClient.KeepAlive = true;
System.IO.FileInfo fi = new System.IO.FileInfo(fileurl);
ftpClient.ContentLength = fi.Length;
byte[] buffer = new byte[4097];
int bytes = 0;
int total_bytes = (int)fi.Length;
System.IO.FileStream fs = fi.OpenRead();
System.IO.Stream rs = ftpClient.GetRequestStream();
while (total_bytes > 0)
{
bytes = fs.Read(buffer, 0, buffer.Length);
rs.Write(buffer, 0, bytes);
total_bytes = total_bytes - bytes;
}
//fs.Flush();
fs.Close();
rs.Close();
FtpWebResponse uploadResponse = (FtpWebResponse)ftpClient.GetResponse();
string value = uploadResponse.StatusDescription;
uploadResponse.Close();
}
Let me know in case of any issue, or here is one more link that can help you:
https://msdn.microsoft.com/en-us/library/ms229715(v=vs.110).aspx
Trying to Find a file and upload it to ftp server, I think i have everything correct but it doesnt upload anything
string filepath = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);
DirectoryInfo d = new DirectoryInfo(filepath);
List<String> allDatfiles = Directory
.GetFiles(filepath, "data.dat", SearchOption.AllDirectories).ToList();
foreach (string file in allDatfiles)
{
FtpWebRequest request = (FtpWebRequest)WebRequest.Create("ftp://www.test.com/Holder");
request.Method = WebRequestMethods.Ftp.UploadFile;
request.Credentials = new NetworkCredential("User", "Pass");
request.UseBinary = true;
request.UsePassive = true;
byte[] data = File.ReadAllBytes(file); // Think the problem is with file
request.ContentLength = data.Length;
Stream stream = request.GetRequestStream();
stream.Write(data, 0, data.Length);
stream.Close();
}
Also tried putting in the file location as a string with #"C...
I receive no errors, and no file shows up after the upload
Did you check the user permission on server.. can user write to
directory?
if you use linux server this will help you to fix file path issue.
private static void UploadFile(string dir, Uri target, string fileName, string username, string password, string finilizingDir, string startupPath, string logFileDirectoryName)
{
try
{
// Get the object used to communicate with the server.
FtpWebRequest request = (FtpWebRequest)WebRequest.Create(target);
request.Proxy = null;
request.Method = WebRequestMethods.Ftp.UploadFile;
// logon.
request.Credentials = new NetworkCredential(username, password);
// Copy the contents of the file to the request stream.
StreamReader sourceStream = new StreamReader(dir + "\\" + fileName);
byte[] fileContents = Encoding.UTF8.GetBytes(sourceStream.ReadToEnd());
sourceStream.Close();
request.ContentLength = fileContents.Length;
Stream requestStream = request.GetRequestStream();
requestStream.Write(fileContents, 0, fileContents.Length);
requestStream.Close();
FtpWebResponse response = (FtpWebResponse)request.GetResponse();
if (response.StatusCode == FtpStatusCode.ClosingData)
{
Console.WriteLine(" --> Status Code is :" + response.StatusCode);
}
Console.WriteLine(" --> Upload File Complete With Status Description :" + response.StatusDescription);
response.Close();
}
catch (Exception ex)
{
Console.WriteLine("*** Error Occurred while uploading file :" + fileName + " System Says :" + ex.Message + " **********END OF ERROR**********");
}
}
How do you copy a file on an FTP server? My goal is to copy ftp://www.mysite.com/test.jpg to ftp://www.mysite.com/testcopy.jpg. To rename a file, I would use:
var request = (FtpWebRequest)WebRequest.Create("ftp://www.mysite.com/test.jpg");
request.Credentials = new NetworkCredential(user, pass);
request.Method = WebRequestMethods.Ftp.Rename;
request.RenameTo = "testrename.jpg"
request.GetResponse().Close();
FtpWebResponse resp = (FtpWebResponse)request.GetResponse();
However, there is no Method for copying files. How would you do copy a file?
Try this:
static void Main(string[] args)
{
CopyFile("countrylist.csv", "MySample.csv", "username", "password#");
}
public static bool CopyFile(string fileName, string FileToCopy, string userName, string password)
{
try
{
FtpWebRequest request = (FtpWebRequest)WebRequest.Create("ftp://ftp.mysite.net/" + fileName);
request.Method = WebRequestMethods.Ftp.DownloadFile;
request.Credentials = new NetworkCredential(userName, password);
FtpWebResponse response = (FtpWebResponse)request.GetResponse();
Stream responseStream = response.GetResponseStream();
Upload("ftp://ftp.mysite.net/" + FileToCopy, ToByteArray(responseStream), userName, password);
responseStream.Close();
return true;
}
catch
{
return false;
}
}
public static Byte[] ToByteArray(Stream stream)
{
MemoryStream ms = new MemoryStream();
byte[] chunk = new byte[4096];
int bytesRead;
while ((bytesRead = stream.Read(chunk, 0, chunk.Length)) > 0)
{
ms.Write(chunk, 0, bytesRead);
}
return ms.ToArray();
}
public static bool Upload(string FileName, byte[] Image, string FtpUsername, string FtpPassword)
{
try
{
System.Net.FtpWebRequest clsRequest = (System.Net.FtpWebRequest)System.Net.WebRequest.Create(FileName);
clsRequest.Credentials = new System.Net.NetworkCredential(FtpUsername, FtpPassword);
clsRequest.Method = System.Net.WebRequestMethods.Ftp.UploadFile;
System.IO.Stream clsStream = clsRequest.GetRequestStream();
clsStream.Write(Image, 0, Image.Length);
clsStream.Close();
clsStream.Dispose();
return true;
}
catch
{
return false;
}
}
This downloads the file to a stream, and then uploads it.
FtpWebRequest is a lightweight class. Microsoft felt it should be used by simple client to download and delete the files once the client is finish.
I guess you can't really do this with FTP. What you can do is download the file you want to copy and then upload it with a new name. For example:
try
{
WebClient request = new WebClient();
request.Credentials = new NetworkCredential(user, pass);
byte[] data = request.DownloadData(host);
MemoryStream file = new MemoryStream(data);
Upload(data);
}
catch (Exception ex)
{
}
...
private void Upload(byte[] buffer)
{
try
{
FtpWebRequest request = (FtpWebRequest)FtpWebRequest.Create(newname);
request.Method = WebRequestMethods.Ftp.UploadFile;
request.Credentials = new NetworkCredential(user, pass);
Stream reqStream = request.GetRequestStream();
reqStream.Write(buffer, 0, buffer.Length);
reqStream.Close();
var resp = (FtpWebResponse)request.GetResponse();
}
catch (Exception ex)
{
}
}
In our project we did someting like this
// pass parameters according to your need,
// the below code is done in a hard coded manner for clarity
public void Copy()
{
// from where you want to copy
var downloadRequest = (FtpWebRequest)WebRequest.Create("ftp://www.mysite.com/test.jpg");
downloadRequest.Credentials = new NetworkCredential("userName", "passWord");
downloadRequest.Method = WebRequestMethods.Ftp.DownloadFile;
var ftpWebResponse = (FtpWebResponse)downloadRequest.GetResponse();
var downloadResponse = ftpWebResponse.GetResponseStream();
int buffLength = 2048;
byte[] byteBuffer = new byte[buffLength];
// bytes read from download stream.
// from documentation: When overridden in a derived class, reads a sequence of bytes from the
// current stream and advances the position within the stream by the number of bytes read.
int bytesRead = downloadResponse.Read(byteBuffer, 0, buffLength);
// the place where you want the file to go
var uploadRequest = (FtpWebRequest)WebRequest.Create("ftp://www.mysite.com/testCopy.jpg");
uploadRequest.Credentials = new NetworkCredential("userName", "passWord");
uploadRequest.Method = WebRequestMethods.Ftp.UploadFile;
var uploadStream = uploadRequest.GetRequestStream();
if (bytesRead > 0)
{
while (bytesRead > 0)
{
uploadStream.Write(byteBuffer, 0, bytesRead);
bytesRead = downloadResponse.Read(byteBuffer, 0, buffLength);
}
}
uploadStream.Close();
uploadStream.Dispose();
downloadResponse.Close();
ftpWebResponse.Close();
((IDisposable)ftpWebResponse).Dispose();
}
Thanks icktoofay,
I tried using HttpWebRequest and HttpWebResponse.
When I request for URL by passing the Credentials like UserName And Password.
I will get the Session Id Back in the Response.
After getting that Session Id, How to Move Further.
The authenticated user are tracked using credentials/cookies.
I'm Having the Exact Url of the File to be downloaded and credentials.
If you want to use Cookies I will. I need to read the File Data and write/save it in a Specified Location.
The code I'm using is;
string username = "";
string password = "";
string reqString = "https://xxxx.com?FileNAme=asfhasf.mro" + "?" +
"username=" + username + &password=" + password;
byte[] requestData = Encoding.UTF8.GetBytes(reqString);
string s1;
CookieContainer cc = new CookieContainer();
var request = (HttpWebRequest)WebRequest.Create(loginUri);
request.Proxy = null;
request.CookieContainer = cc;
request.Method = "POST";
HttpWebResponse ws = (HttpWebResponse)request.GetResponse();
Stream str = ws.GetResponseStream();
//ws.Cookies
//var request1 = (HttpWebRequest)WebRequest.Create(loginUri);
byte[] inBuf = new byte[100000];
int bytesToRead = (int) inBuf.Length;
int bytesRead = 0;
while (bytesToRead > 0)
{
int n = str.Read(inBuf, bytesRead,bytesToRead);
if (n==0)
break;
bytesRead += n;
bytesToRead -= n;
}
FileStream fstr = new FileStream("weather.jpg", FileMode.OpenOrCreate,
FileAccess.Write);
fstr.Write(inBuf, 0, bytesRead);
str.Close();
fstr.Close();
This is how I do it:
const string baseurl = "http://www.some......thing.com/";
CookieContainer cookie;
The first method logins to web server and gets session id:
public Method1(string user, string password) {
HttpWebRequest req = (HttpWebRequest)WebRequest.Create(baseurl);
req.Method = "POST";
req.ContentType = "application/x-www-form-urlencoded";
string login = string.Format("go=&Fuser={0}&Fpass={1}", user, password);
byte[] postbuf = Encoding.ASCII.GetBytes(login);
req.ContentLength = postbuf.Length;
Stream rs = req.GetRequestStream();
rs.Write(postbuf,0,postbuf.Length);
rs.Close();
cookie = req.CookieContainer = new CookieContainer();
WebResponse resp = req.GetResponse();
resp.Close();
}
The other method gets the file from server:
string GetPage(string path) {
HttpWebRequest req = (HttpWebRequest)WebRequest.Create(path);
req.CookieContainer = cookie;
WebResponse resp = req.GetResponse();
string t = new StreamReader(resp.GetResponseStream(), Encoding.Default).ReadToEnd();
return IsoToWin1250(t);
}
Note that I return the page as string. You would probably better return it as bytes[] to save to disk. If your jpeg files are small (they usually are not gigabyte in size), you can simply put them to memory stream, and then save to disk. It will take some 2 or 3 simple lines in C#, and not 30 lines of tough code with potential dangerous memory leaks like you provided above.
public override DownloadItems GetItemStream(string itemID, object config = null, string downloadURL = null, string filePath = null, string)
{
DownloadItems downloadItems = new DownloadItems();
try
{
if (!string.IsNullOrEmpty(filePath))
{
using (FileStream fileStream = new System.IO.FileStream(filePath, System.IO.FileMode.OpenOrCreate, System.IO.FileAccess.Write))
{
if (!string.IsNullOrEmpty(downloadURL))
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(downloadURL);
request.Method = WebRequestMethods.Http.Get;
request.PreAuthenticate = true;
request.UseDefaultCredentials = true;
const int BUFFER_SIZE = 16 * 1024;
{
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
{
using (var responseStream = response.GetResponseStream())
{
var buffer = new byte[BUFFER_SIZE];
int bytesRead;
do
{
bytesRead = responseStream.Read(buffer, 0, BUFFER_SIZE);
fileStream.Write(buffer, 0, bytesRead);
} while (bytesRead > 0);
}
}
fileStream.Close();
downloadItems.IsSuccess = true;
}
}
else
downloadItems.IsSuccess = false;
}
}
}
catch (Exception ex)
{
downloadItems.IsSuccess = false;
downloadItems.Exception = ex;
}
return downloadItems;
}