How to Transfer the .xls file to other FTP Path using C# - c#

I am new to the C#, I need to transfer .xlx file from specified location to FTP path (\ServerHostName\ExtractedFile). using C# code, Could you please help me

The MSDN page for FtpWebRequest contains a few examples dealing with FTP in C# & .NET. One of the examples is exactly what you would like to do, uploading a file. This example is asynchronous.
https://msdn.microsoft.com/en-us/library/system.net.ftpwebrequest(v=vs.110).aspx
On another page, there is a simpler example:
https://msdn.microsoft.com/en-us/library/ms229715(v=vs.110).aspx
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.
StreamReader sourceStream = new StreamReader("testfile.txt");
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();
Console.WriteLine("Upload File Complete, status {0}", response.StatusDescription);
response.Close();
}
}
}
}

Related

FTP stream request stream issue

The error I am getting is web exception. The requested URI is invalid for this FTP command.
I am unsure as how to fix it. Anyone got any idea's? Thanks
private void SendFile(FileInfo file)
{
Console.WriteLine("ftp://" + ipAddressTextField.Text);
// Get the object used to communicate with the server.
string ftp = "ftp://" + ipAddressTextField.Text;
FtpWebRequest request = (FtpWebRequest)WebRequest.Create(ftp);
request.Method = WebRequestMethods.Ftp.UploadFile;
// This example assumes the FTP site uses anonymous logon.
request.Credentials = new NetworkCredential(usernameTextField.Text, passwordTextField.Text);
// Copy the contents of the file to the request stream.
byte[] fileContents = File.ReadAllBytes(file.FullName);
request.ContentLength = fileContents.Length;
Stream requestStream = request.GetRequestStream();
requestStream.Write(fileContents, 0, fileContents.Length);
requestStream.Close();
FtpWebResponse response = (FtpWebResponse)request.GetResponse();
Console.WriteLine("Upload File Complete, status {0}", response.StatusDescription);
response.Close();
}
Seems you're not setting a destination filename for the upload so the server has no file name to use for the uploaded file.
You could just set it the same as the source file name using something like;
string ftp = "ftp://" + ipAddressTextField.Text + "/" + file.Name;
Console.WriteLine(ftp);
To do a slightly more robust creation of the Uri in case that the file names may have special characters, you could use the Uri class to build it, and pass that in to WebRequest.Create instead.

C# console Application Proxy authentication not working

Please assist with the code below.
When I use it on a Pc that doesn't require a proxy and the proxy settings are commented out it works fine but now I have to run the program on a proxy enabled network but it continuously gives me the error:
An unhandled exception of type 'System.Net.WebException' occurred in
System.dll Additional information: The remote server returned an
error: (407) Proxy Authentication Required.
Please note if you try to run the program it wont be able to fetch the data as it needs to be run from a PC whose IP is on the white lists.
Code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.IO;
using System.Xml;
using System.Xml.Linq;
using System.Web;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
//System.Net.WebRequest.GetSystemWebProxy();
string urlDemo = "http://www.api.myoptions.com/api";
// ReadCountries();
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(urlDemo);
request.Credentials = new NetworkCredential("matt.luck", "Mambo88e","JOC");
WebProxy aProxy = new WebProxy();
aProxy.Address = new Uri("Http://182.155.1.205:8080",true)
request.Proxy = aProxy;
// Set the Method property of the request to POST.
request.Method = "POST";
// Create POST data and convert it to a byte array.
string postData = "api_username=usernameapi_password=password";
postData += "&MODULE=Customer&COMMAND=view&FILTER[id]=1";
byte[] byteArray = Encoding.UTF8.GetBytes(postData);
// Set the ContentType property of the WebRequest.
request.ContentType = "application/x-www-form-urlencoded";
// Set the ContentLength property of the WebRequest.
request.ContentLength = byteArray.Length; request.Timeout = 60000;
// Get the request stream.
Stream dataStream = request.GetRequestStream();
// Write the data to the request stream.
dataStream.Write(byteArray, 0, byteArray.Length);
// Close the Stream object.
// Get the response.
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
// Display the status.
Console.WriteLine(((HttpWebResponse)response).StatusDescription);
// Get the stream containing content returned by the server.
dataStream = response.GetResponseStream();
// Open the stream using a StreamReader for easy access.
StreamReader reader = new StreamReader(dataStream);
// Read the content.
string responseFromServer = reader.ReadToEnd();
// Display the content.
Console.WriteLine(responseFromServer);
Console.WriteLine("\nClick On Enter To Close Window");
Console.ReadLine();
// Clean up the streams.
reader.Close();
dataStream.Close();
response.Close();
}
}
}
Make sure your proxy details are correct and provide the credentials to the WebProxy object
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(urlDemo);
request.Credentials = new NetworkCredential("matt.luck", "Mambo88e","JOC");
WebProxy aProxy = new WebProxy();
aProxy.Address = new Uri("Http://182.155.1.205:8080",true)
aProxy.Credentials = new NetworkCredential("matt.luck", "Mambo88e","JOC");

Upload files using ASP.NET

<form action="http://s0.filesonic.com/abc" method="post" enctype="multipart/form-data">
<input type="file" name="files[]" />
<button type="submit">submit</button>
</form>
The above code uploads the files to file sonic server, but I want to do this using programmatically using C#, basically my requirement is that the program creates the form and file control and sends the file to the Filesonic server URL mentioned in action attribute..
I have gone through many links but with no success, I have gone through the following links with no success.
Upload files with HTTPWebrequest (multipart/form-data)
The following code will upload the file to the server as long as the server can accept it outside of files[] array.
WebRequest webRequest = WebRequest.Create("http://s0.filesonic.com/abc");
FileStream reader = new FileStream("file_to_upload", FileMode.Open);
byte[] data = new byte[reader.Length];
webRequest.Method = "POST";
webRequest.ContentType = "multipart/form-data";
webRequest.ContentLength = reader.Length;
webRequest.AllowWriteStreamBuffering = "true";
reader.Read(data, 0, reader.Length);
using (var request = webRequest.GetRequestStream())
{
request.Write(data, 0, data.Length);
using (var response = webRequest.GetResponse())
{
//Do something with response if needed
}
I that case your action on the form would point to your own page on your asp.net server. You are going to post a file back to your asp.net server using http, you will then either hold it in memory or write it to a temp directory, then you could HttpWebRequest to send the file to the filesonic server.
In your case you can also do form a post directly using HttpWebRequest, a quick sample that i could find is here
You can upload file to your server using FTP credentials
Here , path means your local file path or source file & DestinationPath is server path where you have to upload file Ex. 'www.....com/upload/xxx.txt'
FtpWebRequest reqObj = (FtpWebRequest) WebRequest.Create(DestinationPath);
reqObj.Method = WebRequestMethods.Ftp.UploadFile;
reqObj.Credentials = new NetworkCredential(FTP_USERNAME, FTP_PASSWORD);
byte[] fileContents = File.ReadAllBytes(path);
reqObj.ContentLength = fileContents.Length;
Stream requestStream = reqObj.GetRequestStream();
requestStream.Write(fileContents, 0, fileContents.Length);
requestStream.Close();
FtpWebResponse response = (FtpWebResponse)reqObj.GetResponse();
response.Close();

Fetching data behind username/password authentication

I'd like to download some data from a forum. The page containing the data is visible only to registered users. Here's an example webpage containing user data;
http://www.bikeforums.net/member.php/227664-StackOverflow
I'd like to get the data using wget or C#. I tried logging in via Firefox, then passing the cookies file (hopefully containing the login information) to wget. That was more of a makeshift hack and not a real solution, but it still failed. How do I do this properly?
I set up an account for testing if that's helpful.
User: StackOverflow
Pass: so123
Using firebug you can easily get the POST data for the login page and use it to create a WebRequest and Login to the Forum.
The Server create the cookies for authentication and we can use this cookies in the next request on the forum page so the server can authenticate the request and return all the data.
Here I've tested a simple console application that achieves this mechanism.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Globalization;
using System.Web;
using System.Net;
using System.Xml;
using System.Xml.XPath;
using System.Xml.Linq;
using System.IO;
namespace ConsoleApplication2
{
class Program
{
static void Main(string[] args)
{
CookieContainer cookieContainer = new CookieContainer();
HttpWebRequest wpost = (HttpWebRequest) HttpWebRequest.Create("http://www.bikeforums.net/login.php?do=login");
wpost.CookieContainer = cookieContainer;
wpost.Method = "POST";
string postData = "do=login&vb_login_md5password=d93bd4ce1af6a9deccaf0ea844d6c05d&vb_login_md5password_utf=d93bd4ce1af6a9deccaf0ea844d6c05d&s=&securitytoken=guest&url=%2Fmember.php%2F227664-StackOverflow&vb_login_username=StackOverflow&vb_login_password=";
byte[] byteArray = Encoding.UTF8.GetBytes(postData);
// Set the ContentType property of the WebRequest.
wpost.ContentType = "application/x-www-form-urlencoded";
// Set the ContentLength property of the WebRequest.
wpost.ContentLength = byteArray.Length;
// Get the request stream.
System.IO.Stream dataStream = wpost.GetRequestStream();
// Write the data to the request stream.
dataStream.Write(byteArray, 0, byteArray.Length);
// Close the Stream object.
dataStream.Close();
// Get the response.
HttpWebResponse response = (HttpWebResponse) wpost.GetResponse();
// Request
wpost = (HttpWebRequest)WebRequest.Create("http://www.bikeforums.net/member.php/227664-StackOverflow");
//Assing the cookies created on the server to the new request
wpost.CookieContainer = cookieContainer;
wpost.Method = "GET";
response = (HttpWebResponse)wpost.GetResponse();
Stream receiveStream = response.GetResponseStream();
// Pipes the stream to a higher level stream reader with the required encoding format.
StreamReader readStream = new StreamReader(receiveStream, Encoding.UTF8);
//Display the result to console...
Console.WriteLine(readStream.ReadToEnd());
response.Close();
readStream.Close();
Console.Read();
}
}
}

Is it possible to do "Active" mode FTP using FtpWebRequest?

Due to some firewall issues, we need to do FTP using "active" mode (i.e. not by initiating a PASV command).
Currently, we're using code along the lines of:
// 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.
StreamReader sourceStream = new StreamReader("testfile.txt");
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();
response.Close();
But this seems to default to using passive mode; Can we influence this to force it to upload using active mode (in the same way that the command line ftp client does)?
Yes, set the UsePassive property to false.
request.UsePassive = false;

Categories