I have an XML document. I don't want to save that XML in a physical path. How can I upload to ftp having xml document in memory.
So, i want to know whether it is possible to have an object in memory and save to ftp. I have the code for uploading to ftp which takes local path and remote path as parameters and upload it.
UploadXMLToFTP(XmlDocument xml)
//Now this XMLDocument should be uploaded to ftp without saving in physical drive.
Following the MSDN Example of how to upload a file via FTP in .NET:
using System;
using System.IO;
using System.Net;
using System.Text;
...
public static void UploadXMLToFTP (XmlDocument xml)
{
// Get the object used to communicate with the server.
using(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.
request.ContentLength = xml.OuterXml.Length;
Stream requestStream = request.GetRequestStream();
xml.Save(requestStream);
requestStream.Close();
FtpWebResponse response = (FtpWebResponse)request.GetResponse();
Console.WriteLine("Upload File Complete, status {0}", response.StatusDescription);
response.Close();
}
}
Related
I am trying to improve performance for my application by downloading google drive files in compressed format. I am using this as reference.
https://developers.google.com/drive/api/v2/performance#gzip
I tried various things in the header of the HttpwebRequest I am sending , but couldnt achieve success. Can anyone please help me in this regard.
This is the code I am using.
public void DownloadFile(string url, string filename)
{
try
{
var tstart = DateTime.Now;
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.Timeout = 60 * 1000; // Timeout
request.Headers.Add("Authorization", "Bearer" + " " + AuthenticationKey);
request.Headers.Add("Accept-Encoding", "gzip,deflate");
request.UserAgent = "MyApplication/11.14 (gzip)";
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
string content = response.GetResponseHeader("content-disposition");
Console.WriteLine(content);
System.IO.Stream received = response.GetResponseStream();
using (System.IO.FileStream file = new System.IO.FileStream(filename, System.IO.FileMode.Create, System.IO.FileAccess.Write))
{
received.CopyTo(file);
}
var tend = DateTime.Now;
Console.WriteLine("time taken to download '{0}' is {1} seconds", filename, (tend - tstart).TotalSeconds);
}
catch (WebException e)
{
Console.WriteLine("Exception thrown - {0}", e.Message);
}
}
Using gzip
An easy and convenient way to reduce the bandwidth needed for each request is to enable gzip compression. Although this requires additional CPU time to uncompress the results, the trade-off with network costs usually makes it very worthwhile.
In order to receive a gzip-encoded response you must do two things: Set an Accept-Encoding header, and modify your user agent to contain the string gzip. Here is an example of properly formed HTTP headers for enabling gzip compression:
Accept-Encoding: gzip
User-Agent: my program (gzip)
Gzip compress the actual response from the API. Not the actual file you are downloading. For example file.export returns a file.resource json object this object would be compressed. Not the actual data of the file you will need to download. Files are downloaded in their corresponding type manage downloads While google may be able to convert a google doc file to a ms word file when you download it. It is not going to covert a google doc file to a zip file so that you can download it zipped.
I would like to load an excel file directly from an ftp site into a memory stream. Then I want to open the file in the FarPoint Spread control using the OpenExcel(Stream) method. My issue is I'm not sure if it's possible to download a file directly into memory. Anyone know if this is possible?
Yes, you can download a file from FTP to memory.
I think you can even pass the Stream from the FTP server to be processed by FarPoint.
WebRequest request = FtpWebRequest.Create("ftp://asd.com/file");
using (WebResponse response = request.GetResponse())
{
Stream responseStream = response.GetResponseStream();
OpenExcel(responseStream);
}
Using WebClient you can do nearly the same. Generally using WebClient is easier but gives you less configuration options and control (eg.: No timeout setting).
WebClient wc = new WebClient();
using (MemoryStream stream = new MemoryStream(wc.DownloadData("ftp://asd.com/file")))
{
OpenExcel(stream);
}
Take a look at WebClient.DownloadData. You should be able to download the file directory to memory and not write it to a file first.
This is untested, but something like:
var spreadSheetStream
= new MemoryStream(new WebClient().DownloadData(yourFilePath));
I'm not familiar with FarPoint though, to say whether or not the stream can be used directly with the OpenExcel method. Online examples show the method being used with a FileStream, but I'd assume any kind of Stream would be accepted.
Download file from URL to memory.
My answer does not exactly show, how to download a file for use in Excel, but shows how to create a generic-purpose in-memory byte array.
private static byte[] DownloadFile(string url)
{
byte[] result = null;
using (WebClient webClient = new WebClient())
{
result = webClient.DownloadData(url);
}
return result;
}
I am downloading image files from web using the following code in my Console Application.
WebClient client = new WebClient();
client.DownloadFile(string address_of_image_file,string filename);
The code is running absolutely fine.
I want to know if there is a way i can get the size of this image file before I download it.
PS- Actually I have written code to make a crawler which moves around the site downloading image files. So I doesn't know its size beforehand. All I have is the complete path of file which has been extracted from the source of webpage.
Here is a simple example you can try
if you have files of different extensions like .GIF, .JPG, etc
you can create a variable or wrap the code within a Switch Case Statement
System.Net.WebClient client = new System.Net.WebClient();
client.OpenRead("http://someURL.com/Images/MyImage.jpg");
Int64 bytes_total= Convert.ToInt64(client.ResponseHeaders["Content-Length"])
MessageBox.Show(bytes_total.ToString() + " Bytes");
If the web-service gives you a Content-Length HTTP header then it will be the image file size. However, if the web-service wants to "stream" data to you (using Chunk encoding), then you won't know until the whole file is downloaded.
You can use this code:
using System.Net;
public long GetFileSize(string url)
{
long result = 0;
WebRequest req = WebRequest.Create(url);
req.Method = "HEAD";
using (WebResponse resp = req.GetResponse())
{
if (long.TryParse(resp.Headers.Get("Content-Length"), out long contentLength))
{
result = contentLength;
}
}
return result;
}
You can use an HttpWebRequest to query the HEAD Method of the file and check the Content-Length in the response
You should look at this answer: C# Get http:/…/File Size where your question is fully explained. It's using HEAD HTTP request to retrieve the file size, but you can also read "Content-Length" header during GET request before reading response stream.
I'm trying to upload a file to an FTP server using code based on this Microsoft Article
My code looks like this for testing purposes:
string ftpUrl = "ftp://" + ftpSite + ftpPath + "test.txt";
//string ftpUrl = ftpSite;
FtpWebRequest request = (FtpWebRequest)WebRequest.Create(ftpUrl);
request.Credentials = new NetworkCredential(ftpUsername, ftpPassword);
request.Method = WebRequestMethods.Ftp.UploadFile;
StreamReader srcStream = new StreamReader(filePath);
byte[] fileContents = Encoding.UTF8.GetBytes(srcStream.ReadToEnd());
request.ContentLength = fileContents.Length;
Stream requestStream = request.GetRequestStream();
requestStream.Write(fileContents, 0, fileContents.Length);
requestStream.Close();
FtpWebResponse response = (FtpWebResponse)request.GetResponse();
Every time I try to upload the file, I get a "Filename not allowed" error back from the FTP server. If I use an FTP client application like WS_FTP, I'm able to FTP the same file just fine.
Any thoughts on how to correct this? I've already tried setting active/passive FTP mode, keepalive, and binary modes without any luck.
EDIT
This is a winforms application - the filename comes in from an OpenFileDialog prompt and the FTP address is based on settings in App.Config.
Without seeing your full code, I will say there is a very good chance the constructed FTP URL / path is incorrect, in comparison to what you expect it to be when you manually connect to the FTP site through a FTP client.
If you post your app.config code and how you assign values to ftpSite and ftpPath, it would be helpful in answering this question.
You can get that particular error for many cases.
Most common issue is that the path you are accessing is not valid by the permissions allowed, and using a relative path or changing thew path might get it fixed.
I am working on the task that, I need to upload the images to particular FTP by using C# coding from given live path.
At the moment I done it, but to upload images on FTP I take round trip of (download the images
on local and then upload it to live by using code).
I want the solution to directly upload images to to ftp without downloading it.
eg. From given path http://www.globalgear.com.au/products/bladesbook_sml.jpg
I need this image to upload.
hello, I am rectifying my question more, I want to fetch Small and large images from this URL(globalgear.com.au/productfeed.xml) and upload directly to FTP without downloading it on local. –
Please suggest any solution.
Thanks
Chetan
Perhabs this will work:
// 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();