Passing File name from textBox to WebRequest.Create in c# - c#

Im working on some small app, and need to upload a text file to ftp.
I use this code to upload a file :
using System;
using System;
using System.IO;
using System.Net;
using System.Text;
/// <summary>
/// Simple static class for uploading a file to an FTP server.
/// </summary>
public static class fileUpload
{
public static string uploadFile(string file)
{
// Get the object used to communicate with the server.
FtpWebRequest request = (FtpWebRequest)WebRequest.Create("ftp://www.mywebserver.com/myfile.txt");
request.Method = WebRequestMethods.Ftp.UploadFile;
// This example assumes the FTP site uses anonymous logon.
request.Credentials = new NetworkCredential("username", "password");
// Copy the entire contents of the file to the request stream.
StreamReader sourceStream = new StreamReader(file);
byte[] fileContents = Encoding.UTF8.GetBytes(sourceStream.ReadToEnd());
sourceStream.Close();
request.ContentLength = fileContents.Length;
// Upload the file stream to the server.
Stream requestStream = request.GetRequestStream();
requestStream.Write(fileContents, 0, fileContents.Length);
requestStream.Close();
// Get the response from the FTP server.
FtpWebResponse response = (FtpWebResponse)request.GetResponse();
// Close the connection = Happy a FTP server.
response.Close();
// Return the status of the upload.
return response.StatusDescription;
}
}
To upload a file i use this :
fileUpload.uploadFile(uploadedfile.txt);
The problem comes when the file uploaded is always named us myfile.txt , i need the name of the file to be exactly as text in textBox1.
So for example i used this when saving file on harddrive ("C:/savehere/"+textBox1.text +".txt");
and it worked fine.
But when i do the same here :
FtpWebRequest request = (FtpWebRequest)WebRequest.Create("ftp://www.mywebserver.com/"+ textBox1.text + ".txt");
it wont work.
How can i do the same in this example ?
Thank you !

If the path is ftp://www.mywebserver.com/filename.txt
Try change to
FtpWebRequest request = (FtpWebRequest)WebRequest.Create("ftp://www.mywebserver.com/%2f"+ textBox1.text + ".txt");
However, it may be better to create a directory to keep the files
ftp://www.mywebserver.com/%2ftemp/filename.txt
UPDATE --
public static class fileUpload
{
TextBox textBox1 = new TextBox();
public static void getText(TextBox tb) {
return tb.text;
}
public static string uploadFile(string file)
{
var aText = getText(textBox1);
// Get the object used to communicate with the server.
FtpWebRequest request = (FtpWebRequest)WebRequest.Create("ftp://www.mywebserver.com/%2f"+ aText + ".txt");
// ....

When i do that it comes back with an error :Error 1 An object reference is required for the non-static field, method, or property 'WindowsFormsApplication1.Form1.textBox7
I understand that this is due to static, but i have no idea how to change it to correct type :(

What about?
string baseUrl = "ftp://www.mywebserver.com/";
string FileName = textBox1.Text;
string extension = ".txt";
FtpWebRequest request = (FtpWebRequest)WebRequest.Create(new Uri(new Uri(baseUrl), string.Format("{0}{1}", FileName, extension)));
this will result in:
ftp://www.mywebserver.com/{textboxContent}.txt

Related

Uploading files to ftp folder having special characters in name

I am trying to upload a file on FTP folder, but getting the following error.
The remote server returned an error: (550) File unavailable (e.g.,
file not found, no access)
I am using the following sample to test this:
// Get the object used to communicate with the server.
string path = HttpUtility.UrlEncode("ftp://host:port//01-03-2017/John, Doe S. M.D/file.wav");
FtpWebRequest request = (FtpWebRequest)WebRequest.Create(path);
request.Method = WebRequestMethods.Ftp.UploadFile;
// This example assumes the FTP site uses anonymous logon.
request.Credentials = new NetworkCredential("user", "password");
// Copy the contents of the file to the request stream.
StreamReader sourceStream = new StreamReader(#"localpath\example.wav");
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();
I am able to upload files on the parent folder 01-03-2017 but not in the target folder ROLLINS, SETH S. M.D which clearly has special characters in it.
I am able to upload files using FileZilla
I have tried to HttpUtility.UrlEncode but that did n't help
Thanks for your time and help.
You need to encode the spaces (and maybe commas) in the URL path, like:
string path =
"ftp://host:port/01-03-2017/" +
HttpUtility.UrlEncode("John, Doe S. M.D") + "/file.wav";
Effectively, you get:
ftp://host:port/01-03-2017/John%2c+Doe+S.+M.D/file.wav
Use something like this:
string path = HttpUtility.UrlEncode("ftp://96.31.95.118:2121//01-03-2017//ROLLINS, SETH S. M.D//30542_3117.wav");
or You can form a Uri using the following code and pass it webrequest.
var path = new Uri("ftp://96.31.95.118:2121//01-03-2017//ROLLINS, SETH S. M.D//30542_3117.wav");
The code works on a C# console application but did not work in Web Api Action. I could not manage to find the reason.
So I have used a free library for the same.
Posting the sample code from one of the examples available here:
So i have used FluentFtp libary available through Nuget.
using System;
using System.IO;
using System.Net;
using FluentFTP;
namespace Examples {
public class OpenWriteExample {
public static void OpenWrite() {
using (FtpClient conn = new FtpClient()) {
conn.Host = "localhost";
conn.Credentials = new NetworkCredential("ftptest", "ftptest");
using (Stream ostream = conn.OpenWrite("01-03-2017/John, Doe S. M.D/file.wav")) {
try {
// istream.Position is incremented accordingly to the writes you perform
}
finally {
ostream.Close();
}
}
}
}
}
}
Again, if the file is a binary file, StreamReader should not be used as explained here.

Pulling CSV file from server and displaying on a site [duplicate]

Im trying to create a web service which gets to a URL e.g. www.domain.co.uk/prices.csv and then reads the csv file. Is this possible and how? Ideally without downloading the csv file?
You could use:
public string GetCSV(string url)
{
HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
HttpWebResponse resp = (HttpWebResponse)req.GetResponse();
StreamReader sr = new StreamReader(resp.GetResponseStream());
string results = sr.ReadToEnd();
sr.Close();
return results;
}
And then to split it:
public static void SplitCSV()
{
List<string> splitted = new List<string>();
string fileList = getCSV("http://www.google.com");
string[] tempStr;
tempStr = fileList.Split(',');
foreach (string item in tempStr)
{
if (!string.IsNullOrWhiteSpace(item))
{
splitted.Add(item);
}
}
}
Though there are plenty of CSV parsers out there and i would advise against rolling your own. FileHelpers is a good one.
// Download the file to a specified path. Using the WebClient class we can download
// files directly from a provided url, like in this case.
System.Net.WebClient client = new WebClient();
client.DownloadFile(url, csvPath);
Where the url is your site with the csv file and the csvPath is where you want the actual file to go.
In your Web Service you could use the WebClient class to download the file, something like this ( I have not put any exception handling, not any using or Close/Dispose calls, just wanted to give the idea you can use and refine/improve... )
using System.Net;
WebClient webClient = new WebClient();
webClient.DownloadFile("http://www.domain.co.uk/prices.csv");
then you can do anything you like with it once the file content is available in the execution flow of your service.
if you have to return it to the client as return value of the web service call you can either return a DataSet or any other data structure you prefer.
Sebastien Lorion's CSV Reader has a constructor that takes a Stream.
If you decided to use this, your example would become:
void GetCSVFromRemoteUrl(string url)
{
HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
HttpWebResponse response = request.GetResponse() as HttpWebResponse;
using (CsvReader csvReader = new CsvReader(response.GetResponseStream(), true))
{
int fieldCount = csvReader.FieldCount;
string[] headers = csvReader.GetFieldHeaders();
while (csvReader.ReadNextRecord())
{
//Do work with CSV file data here
}
}
}
The ever popular FileHelpers also allows you to read directly from a stream.
The documentation for WebRequest has an example that uses streams. Using a stream allows you to parse the document without storing it all in memory

c# / More effective way to upload file with ftp

I'm uploading a .txt file with c# and:
client.Credentials = new NetworkCredential(ftpU, ftpP);
client.UploadFile("here ftp server", "STOR", lfilepath);
And sometimes it just throws error like "System Error"
This .txt is just log in information, content of this txt is like User: Name At: 2015/12/12 08:43 AM
Is there any option to eliminate this error? Make ftp upload more effective? Or any idea to save log on informations in Internet.
Try to use FtpWebRequest and WebRequestMethods.Ftp.UploadFile. Here is the piece of code which we use for uplaoding files from ZipArchive to FTP (so there is also an option showing creating a directories if you need it too). From all methods which I've tested it was the most efficient one.
//// Get the object used to communicate with the server.
var request =
(FtpWebRequest)
WebRequest.Create("ftp://" + ftpServer + #"/" + remotePath + #"/" +
entry.FullName.TrimEnd('/'));
//// Determine if we are transferring file or directory
if (string.IsNullOrWhiteSpace(entry.Name) && !string.IsNullOrWhiteSpace(entry.FullName))
request.Method = WebRequestMethods.Ftp.MakeDirectory;
else
request.Method = WebRequestMethods.Ftp.UploadFile;
//// Try to transfer file
try
{
//// This example assumes the FTP site uses anonymous logon.
request.Credentials = new NetworkCredential(user, password);
switch (request.Method)
{
case WebRequestMethods.Ftp.MakeDirectory:
break;
case WebRequestMethods.Ftp.UploadFile:
var buffer = new byte[8192];
using (var rs = request.GetRequestStream())
{
StreamUtils.Copy(entry.Open(), rs, buffer);
}
break;
}
}
catch (Exception ex)
{
//// Handle it!
LogHelper.Error<FtpHelper>("Could not extract file from package.", ex);
}
finally
{
//// Get the response from the FTP server.
var response = (FtpWebResponse) request.GetResponse();
//// Close the connection = Happy a FTP server.
response.Close();
}

Download file for reading question using HttpWebRequest

If I have a URL to a download, www.website.com/myfile.html
so when that link is clicked it automatically starts a download, which may be myfile.txt for example, how would I get that file into C# for reading..
Is that what Net.WebRequest.Create(url), Net.HttpWebRequest does?
You could achieve this using WebClient:
using (var client = new WebClient())
{
// Download and save the file locally
client.DownloadFile("http://www.website.com/myfile.html", "myfile.html");
}
If you don't want to store the file locally but only read the contents you could try this:
using (var client = new WebClient())
{
string result = client.DownloadString("http://www.website.com/myfile.html");
}
Using C# as an example, here is how one might force the download of a file after clicking a button, link, etc...
public void DownloadFileLink_Click(object sender, EventArgs e)
{
//Get the file data
byte[] fileBytes = Artifacts.Provider.GetArtifact(ArtifactInfo.Id);
//Configure the response header and submit the file data to the response stream.
HttpContext.Current.Response.AddHeader("Content-disposition", "attachment;filename=" + "myDynamicFileName.txt");
HttpContext.Current.Response.ContentType = "application/octet-stream";
HttpContext.Current.Response.BinaryWrite(fileBytes);
HttpContext.Current.Response.End();
}
With this in mind, what you need to look for is the Header in the response, the Header will contain an item Content-disposition which will contain the filename of the file being streamed in the response.

How to check if a file exists on a server using c# and the WebClient class

In my application I use the WebClient class to download files from a Webserver by simply calling the DownloadFile method. Now I need to check whether a certain file exists prior to downloading it (or in case I just want to make sure that it exists). I've got two questions with that:
What is the best way to check whether a file exists on a server without transfering to much data across the wire? (It's quite a huge number of files I need to check)
Is there a way to get the size of a given remote file without downloading it?
Thanks in advance!
WebClient is fairly limited; if you switch to using WebRequest, then you gain the ability to send an HTTP HEAD request. When you issue the request, you should either get an error (if the file is missing), or a WebResponse with a valid ContentLength property.
Edit: Example code:
WebRequest request = WebRequest.Create(new Uri("http://www.example.com/"));
request.Method = "HEAD";
using(WebResponse response = request.GetResponse()) {
Console.WriteLine("{0} {1}", response.ContentLength, response.ContentType);
}
When you request file using the WebClient Class, the 404 Error (File Not Found) will lead to an exception. Best way is to handle that exception and use a flag which can be set to see if the file exists or not.
The example code goes as follows:
System.Net.HttpWebRequest request = null;
System.Net.HttpWebResponse response = null;
request = (System.Net.HttpWebRequest)System.Net.HttpWebRequest.Create("www.example.com/somepath");
request.Timeout = 30000;
try
{
response = (System.Net.HttpWebResponse)request.GetResponse();
flag = 1;
}
catch
{
flag = -1;
}
if (flag==1)
{
Console.WriteLine("File Found!!!");
}
else
{
Console.WriteLine("File Not Found!!!");
}
You can put your code in respective if blocks.
Hope it helps!
What is the best way to check whether a file exists on a server
without transfering to much data across the wire?
You can test with WebClient.OpenRead to open the file stream without reading all the file bytes:
using (var client = new WebClient())
{
Stream stream = client.OpenRead(url);
// ^ throws System.Net.WebException: 'Could not find file...' if file is not present
stream.Close();
}
This will indicate if the file exists at the remote location or not.
To fully read the file stream, you would do:
using (var client = new WebClient())
{
Stream stream = client.OpenRead(url);
StreamReader sr = new StreamReader(stream);
Console.WriteLine(sr.ReadToEnd());
stream.Close();
}
In case anyone stuck with ssl certificate issue
ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback
(
delegate { return true; }
);
WebRequest request = WebRequest.Create(new Uri("http://.com/flower.zip"));
request.Method = "HEAD";
using (WebResponse response = request.GetResponse())
{
Console.WriteLine("{0} {1}", response.ContentLength, response.ContentType);
}

Categories