Is there a way to download a file without Webclient in Silverlight? - c#

I am in a situation where I have to download one file into Bytearray and make some changes in that byte array, also at the same time I have to download another large file and merge the first file into it with the modified bytes on the fly and play it using MediaElement.
Using Webclient I am able to download file but the webclient only gives me access to its dwonloaded bytearray when the file download is complete.
Is there a way to download the file and make modifications to the file's byte array on the fly in Silverlight.
I can not use Sockets, I can only download files from a Webserver.
Any help from you Gurus are appreciated

I can't see what is the problem with the Webclient.
You should copy the results of the WebClients in byte arrays.
Once every file has been downloaded, you can merge those byte arrays.
byte[] bytes;
public void DownloadFile()
{
WebClient webClient = new WebClient();
webClient.OpenReadCompleted += (s, e) =>
{
Stream stream = e.Result;
MemoryStream ms = new MemoryStream();
stream.CopyTo(ms);
bytes = ms.ToArray();
};
webClient.OpenReadAsync(new Uri("http://myurl.com/file.zip"), UriKind.Absolute);
}

Related

Read file from Azure into MemoryStream C#

I have an ini config file located on Azure. I don't want to download this file which is how its currently being handled. I want to read it into a MemoryStream and parse it from there and then have the MemoryStream automatically flush the data.
Is there any way to do this without having to download the file itself onto the local drive?
Current download method is:
myWebClient.DownloadFile("AzureLink", #"C:\\Program Files (x86)\\MyProgram\\downloadedFile.ini")
I assume this is what you're looking for:
WebClient wc = new WebClient();
using (MemoryStream stream = new MemoryStream(wc.DownloadData(url)))
{
//your code in here
}

Audio file is not working via FTP upload programatically

I am uploading an .mp3 file via FTP code using C#, the file is uploaded successfully on server but when i bind to a simple audio control or directly view in browser it does not work as expected, whereas when i upload manually on the server it works perfectly.
Code:
var inputStream = FileUpload1.PostedFile.InputStream;
byte[] fileBytes = new byte[inputStream.Length];
inputStream.Read(fileBytes, 0, fileBytes.Length);
Note: When i view the file in Firefox it shows MIME type is not supported.
Thanks!
You're reading the file as a string then using UTF8 encoding to turn it into bytes. If you do that, and the file contains any binary sequence that doesn't code to a valid UTF8 value, parts of the data stream will simply get discarded.
Instead, read it directly as bytes. Don't bother with the StreamReader. Call the Read() method on the underlying stream. Example:
var inputStream = FileUpload1.PostedFile.InputStream
byte[] fileBytes = new byte[inputStream.Length];
inputStream.Read(fileBytes, 0, fileStream.Length);

Download file directly to memory

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;
}

Cannot download .pdf file in Silverlight

I am fairly new to Silverlight. I am trying to download a .pdf file (and a couple of other formats) in Silverlight. The user clicks a button, the system goes and gets the URI, then shows a SaveFileDialog to obtain the location to save the file. Here is a code snippet:
WebClient wc = new WebClient();
wc.DownloadStringCompleted += (s, e3) =>
{
if (e3.Error == null)
{
try
{
byte[] fileBytes = Encoding.UTF8.GetBytes(e3.Result);
using (Stream fs = (Stream)mySaveFileDialog.OpenFile())
{
fs.Write(fileBytes, 0, fileBytes.Length);
fs.Close();
MessageBox.Show("File successfully saved!");
}
}
catch (Exception ex)
{
MessageBox.Show("Error getting result: " + ex.Message);
}
}
else
{
MessageBox.Show(e3.Error.Message);
};
wc.DownloadStringAsync("myURI", UriKind.RelativeOrAbsolute));
The file gets saved OK, but it is about twice as big as the original and is unreadable. e3.Result looks about the right size (5Mb), but I suspect it contains a lot of extraneous characters. FileBytes seems to be about two times too big (11Mb). I wanted to try DownloadDataAsync instead of DownloadStringAsync (hoping it would resolve any encoding issues), but Silverlight has a very cut-down version of System.Net.WebClient and does not support DownloadDataAsync (it won't compile).
I am fairly sure it is an encoding problem, but I cannot see how to get around it.
PDF files are binary and not encoded using UTF8. To download a PDF file using Silverlight you need to use the OpenReadAsync method of the WebClient class to start downloading the binary data of the file, and not the DownloadStringAsync method as you seem to be doing.
Instead of handling the DownloadStringCompleted event you should handle the OpenReadCompleted event and write the received bytes to the stream of the local PDF file. If you set the AllowReadStreamBuffering to true the OpenReadCompleted event is only fired when the entire file has been downloaded providing you with the same behavior as the DownloadStringCompleted. However, the entire PDF file will be buffered in memory which may be a bad idea if the file is very large.

How to avoid the 0-byte file on Webclient download error

When using the following code to download a file:
WebClient wc = new WebClient();
wc.DownloadFileCompleted += new System.ComponentModel.AsyncCompletedEventHandler(wc_DownloadFileCompleted);
wc.DownloadFileAsync("http://path/file, "localpath/file");
and an error occurs during the download (no internet connection, file not found, etc.)
it allocates a 0-byte file in localpath/file which can get quite annoying.
is there a way to avoid that in a clean way?
(i already just probe for 0 byte files on a download error and delete it, but i dont think that is the recommended solution)
If you reverse engineer the code for WebClient.DownloadFile you will see that the FileStream is instantiated before the download even begins. This is why the file will be created even if the download fails. There's no way to ammend that code so you should cosnider a different approach.
There are many ways to approach this problem. Consider using WebClient.DownloadData rather than WebClient.DownloadFile and only creating or writing to a file when the download is complete and you are sure you have the data you want.
WebClient client = new WebClient();
client.DownloadDataCompleted += (sender, eventArgs) =>
{
byte[] fileData = eventArgs.Result;
//did you receive the data successfully? Place your own condition here.
using (FileStream fileStream = new FileStream("C:\\Users\\Alex\\Desktop\\Data.rar", FileMode.Create))
fileStream.Write(fileData, 0, fileData.Length);
};
client.DownloadDataAsync(address);
client.Dispose();

Categories