Difference between FileStream and WebClient - c#

So, I'm actually trying to setup a Wopi Host for a Web project.
I've been working with this sample (the one from Shawn Cicoria, if anyone knows this), and he provides a whole code sample which tells you how to build the links to use your Office Web App servers with some files.
My problem here, is that his sample is working with files that are ON the OWA server, and i need it to work with online files (like http://myserv/res/test.docx. So when he reads his file content, he's using this :
var stream = new FileStream(myFile, FileMode.Open, FileAccess.Read);
responseMessage.Content = new StreamContent(stream);
But that ain't working on "http" files, so i changed it with this :
byte[] tmp;
using (WebClient client = new WebClient())
{
client.Credentials = CredentialCache.DefaultNetworkCredentials;
tmp = client.DownloadData(name);
}
responseMessage.Content = new ByteArrayContent(tmp);
which IS compiling. And with this sample, i managed to open excel files in my office web app, but words and powerpoint files aren't opened. So, here's my question.
Is there a difference between theses two methods, which could alter the content of the files that i'm reading, despite the fact that the WebClient alows "online reading" ?
Sorry for the unclear post, it's not that easy to explain such a problem x) I did my best.
Thanks four your help !

Is there a difference between theses two methods, which could alter
the content of the files that i'm reading, despite the fact that the
WebClient allows "online reading"
FileStream open a file handle to a file placed locally on disk, or a remote disk sitting elsewhere inside a network. When you open a FileStream, you're directly manipulating that particular file.
On the other hand, WebClient is a wrapper around the HTTP protocol. It's responsibility is to construct HTTP request and response messages, allowing you to conveniently work with them. It has no direct knowledge of a resources such as a file, or particularly where it's located. All it knows is to construct message complying with the specification, sends a request and expects a response.

Related

C# Cant to download JDK15

I'm trying to download JDK15 but i downloading 5307 bytes but this are not the JDK15
using (WebClient wc = new WebClient())
{
wc.DownloadFileAsync(new System.Uri(
"https://download.oracle.com/otn-pub/java/jdk/15.0.1%2B9/51f4f36ad4ef43e39d0dfdbaf6549e32/jdk-15.0.1_windows-x64_bin.exe"),
Path.Combine(directoryPackagesPath, "jdk.exe")
);
}
You downloaded a web page instructing you how to access the download:
You cannot directly download that file. If you open it in another browser, or a incognito/private window, you will see this message:
Sorry!
In order to download products from Oracle Technology Network you must
agree to the OTN license terms.
If you open the downloaded file, most likely it's an HTML with this message.
It is illegal, but if you want learn how to do it for some CTF etc.:
Get query what is send after accepting licence by dev tools in your browser.
Send the exact same query by HttpClient and get cookies from response.
Use this cookies to get the file.
If you want this particular version, you can attach it (if licence allows you to do that) to your program by using installer, by resources or even as normal file in output directory.

C# FTP download files slow

I have a question regarding the ftp library from C#. I need to download 9000 txt files from a ftp server. Station.ToUpper() is the file name, so for every file I need a new ftp connection. For one file it takes around one second. The txt files contain two lines. So for all files it takes around one and a half hour. Is there a better / faster solution?
// Get the object used to communicate with the server.
FtpWebRequest request = (FtpWebRequest)WebRequest.Create(ftpAddress + station.ToUpper());
//request.UsePassive = false;
request.Method = WebRequestMethods.Ftp.DownloadFile;
// This example assumes the FTP site uses anonymous logon.
request.Credentials = new NetworkCredential("anonymous", "janeDoe#contoso.com");
FtpWebResponse response = (FtpWebResponse)request.GetResponse();
Stream responseStream = response.GetResponseStream();
StreamReader reader = new StreamReader(responseStream);
There's not much you're doing wrong in this code, except for the fact you're not calling Dispose() on your streams or response objects. Do that first to make sure you're not somehow running out of resources on the client or something.
Other than that, you don't have too many options here, and a lot depends upon what you can do on the server side.
First, you could try to use threading to download a bunch of files at once. You'll need to experiment with how this affects your throughput. It will probably scale linearly for a while, then fall off. If you open up too many connections, you could anger the maintainer of the server, or it could start denying you connections. Be conservative.
Optimally, the files would be zipped (.ZIP or .TGZ) on the server. This will likely not be an option if you don't have more control over the process.
Use the MGET command to avoid re-establishing a connection each time. The System.Net client does not support MGET, so you would have to use a third party library or script ftp.exe. Regardless of the client you choose, the FTP log would look like the following:
USER anonymous
PASS janeDoe#contoso.com
CWD path/to/file
// to get 3 named files
MGET file1.txt file2.txt file3.txt
// or to get all files matching a pattern
MGET *.txt
The file transfers will use the same control session, avoiding login and other network overhead.
One library which could be of interest is FTPLib, which avoids tearing down the channel on each command. Be careful, however, as FTPLib is based on wininet which is not allowable for use in an NT Service.
I would also take a look at LumiSoft, an open source project with a friendly license, and DotNetFtpLib, though I have used neither and cannot speak to their stability or featureset. On the scripting side, take a look at "Using FTP Batch Scripts".

Downloading a file in C# incorrectly returns files that is zero bytes long

So I'm trying to Download a file using WebClient class but the problem is that when the download is finished the file that should be downloaded is 0 byte, I tried uploading the same file without extension and than changing it after download but that didn't help. What Can I do? This is the code I Use
WebClient updateDownloader = new WebClient();
updateDownloader.DownloadFile(new Uri("http://zazaia.ucoz.com/SomeExeFile.exe"),
Application.StartupPath + "\\SomeFile.EXE");
And also have DownloadCompleted event handler which just shows MessageBox and Disposes the WebClient.
There is nothing wrong with the code you have shown and this should work. The problem is on the server which is not returning the file properly. Also make sure that the site you are querying doesn't require some authentication before being able to download files. In addition to that don't forget that a WebClient will not execute any javascript, so if the server relies on it to download the file, this will not happen.
Have you checked that your antivirus is not interfering? Sometimes an automatic scan will lock an executable file being downloaded until it passes. The client code itself looks fine however.
What about the server side? If is one of your own applications serving the download, then it may not be setting the MIME header or even not handling the download correctly at all

Write file to URL Location using c#

I want to write a file to a virtual directory path in same cloud.
For writing files to local we use
File.WriteAllText('c:\temp\sample.text',string)
Similarly, i want to write to network system like.
File.WriteAllText('\\\10.11.144.29\e$\projects\Map.text',string)
And to virtual directory location like.
File.WriteAllText('http://10.11.144.29/map/test.svg',string)
Is it possible to to write to URL location using c#? if possible, What class can be used?
Any help will be appreciated.
WebClient client = new WebClient();
//client.Credentials = new NetworkCredential("username", "password");
client.UploadFile("http://10.11.144.29/map/test.svg","test.svg");
The last option isn't possible as you require an HTTP PUT or POST to be able to send binary data to a URL, using the HttpWebClient classes or similar.
Examples #1 and #2 you gave should be just fine, though, providing the code running has sufficient permissions at the given network location (i.e. write access)
File.WriteAllText(Server.MapPath(#"c:\temp\sample.text"),string).*

How to download big video files using WebClient class

I'm a newbie and I'm developing a windows application. I need to download a video file from my site and that's my issue here. I had designed a custom down-loader, through which I can download images, text files from my site. But I wasn't able download videos from my site. Could anyone please help me out..?
WebClient client = new WebClient();
client.DownloadProgressChanged += new DownloadProgressChangedEventHandler(client_DownloadProgressChanged);
client.DownloadFileCompleted += new AsyncCompletedEventHandler(client_DownloadFileCompleted);
client.DownloadFileAsync(new Uri("http://mysitename.com/Videos/vid.mp4"), "c:\\movie.mp4");
I don't want to download by means of response content dispatch because my client wants me to download through custom browser.. so please let me know solutions from you experts.. thank you
I have tried to download a video file with WebClient and it works. My setup is as below:
I have a virtualdirectory(Video) in defaultwebsite (IIS) which has this video file.
I just use the below code to download the video file to C drive:
var client = new WebClient();
Uri address = new Uri("http://localhost/Video/wildlife.wmv");
client.DownloadFileAsync(address, #"c:\video.wmv");
Also note since you are downloading in Async fashion, wait for about a min for the operation to complete for the full file to be downloaded. Initially it shows 0 bytes but based on the size it takes some time to complete it.
UPDATE: If your server doesnt have the file mime type specified then just add to the collection of mime types that IIS can serve and you can download the file without any problem.
When adding MIME type the following values to be used are (for your scenario):
File Extension: .mp4
MIME Type: video/mp4
To add mime types in IIS follow these links:
For IIS 4,5
For IIS 6
For IIS 7
This sounds more like a server issue, but if you are doubting your code, you may want to try download sync (I have had some issues in the past downloading async). Another way is to use the WebRequest class. If this server is very remote, try pinging beforehand. I think that you should also check to make sure the file is on the server, and if the file is really big, you should check to see if the file finished uploading.

Categories

Resources