Downloading encrypted binary file using C# Windows Phone is missing data - c#

I need to download an encrypted xml binary file from a url which has been encrypted using JAVA. I have managed to encrypt the file in JAVA, then add the file in my WP7 project and decrypt using c# and read the file into my app succesfully.
I need to now store the file on a web server so the app can access it and I'm finding that the file is not complete or in the incorrect format when I download it and the decryption does not work.
I have tried using both WebClient and HttpWebRequest and both give me the same result. The xml encoded file is approximately 17000 bytes but the file downloaded from both of these methods return a file about 16000 bytes long. I think the downloaded file is missing end of line characters but I can't verify this. The code I'm using at the moment to download the file is pretty simple and is as follows:
private void GetFile()
{
WebClient client = new WebClient();
client.DownloadStringCompleted += new DownloadStringCompletedEventHandler(client_DownloadStringCompleted);
String url = "http://url/encodedfile.txt";
client.DownloadStringAsync(new Uri(url));
}
void client_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
{
string s = e.Result;
byte[] encodedFile = System.Text.Encoding.UTF8.GetBytes(e.result);
//decrypt file....
Looking at the encrypted data they look very similar but the length of encodedFile is not the correct length of the original encrypted file.I've debugged this and copied the characters in encodedFile to TextPad its all on one line. I'm not sure if that's the issue or not but I've looked everywhere on how to download a binary file and most suggestions are to use HttpWebRequest but I get the exact same result so I don't think that is the issue.
Any help appreaciated.

DownloadString will try to read the data as an unicode string. Since you're downloading binary data, it's no wonder the output isn't correct. Try using WebClient.OpenReadAsync instead:
private void GetFile()
{
var webClient = new WebClient();
webClient.OpenReadCompleted += OpenReadCompleted;
string url = "http://url/encodedfile.txt";
webClient.OpenReadAsync(new Uri(url));
}
private void OpenReadCompleted(object sender, OpenReadCompletedEventArgs e)
{
// Decrypt the contents of e.Result
}

Related

Send txt file through URL with c# & PHP?

So basically I've been trying to figure a way to send a text file i receive from a users computer, (Im doing this to allow users to upload certain text files to my website, kinda like storage(i know it sounds kinda stupid)) then once its retrieved i will send the data (from the text file) to my website using the following code:
private void Form1_Load(object sender, EventArgs e)
{
string userDocPath = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
string Path_ = Path.Combine(userDocPath, "RevTech", "Source", "Custom.txt");
WebClient wc = new WebClient();
string txt = File.ReadAllText(Path_);
wc.DownloadString("https://example.com/k/gettext.php?source="+txt);
}
Once that is called i have a page hosted on my server that uses PHP to $_GET['source'] then i use this and use
$myfile = fopen("test.txt", "w") or die("Unable to open file!");
fwrite($myfile, $_GET['source']);
fclose($myfile);
Then when i check to see if the text file was successfully added to my server it doesn't correctly? Hopefully you all understand my question, if you did do any of you possibly have a solution to it? By the way sorry for my bad English

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();

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

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

WebClient.DownloadFile vs. WebClient.DownloadData

I am using WebClient.DownloadFile to download a small executable file from the internet. This method is working very well. However, I would now like to download this executable file into a byte array rather than onto my hard drive. I did some reading and came across the WebClient.DownloadData method. The problem that I am having with the downloadData method is that rather than downloading my file, my code is downloading the HTML data behind my file's download page.
I have tried using dozens of sites - each brings me the same issue. Below is the code I am using.
// Create a new instance of the System.Net 'WebClient'
System.Net.WebClient client = new System.Net.WebClient();
// Download URL
Uri uri = new Uri("http://www35.multiupload.com:81/files/4D7B4D2BFC3F1A9F765A433BA32ED2C5883D0CE133154A0FDB7E7786547A3165DA62393141C4AF8FF36C75222566CF3EB64AF6FBCFC02099BB209C891529CF7B90C83D9C63D39D989CBB8ECE6DE2B83B/Project1.exe");
byte[] dbytes = client.DownloadData(uri);
MessageBox.Show(dbytes.Length.ToString()); // Not the size of my file
Keep in mind that I am attempting to download the data of an executable file into a byte array.
Thank you for any help,
Evan
You are attempting to download a file using an expired token url. See below:
URL: http://www35.multiupload.com:81/files/4D7B4D2BFC3F1A9F765A433BA32ED2C5883D0CE133154A0FDB7E7786547A3165DA62393141C4AF8FF36C75222566CF3EB64AF6FBCFC02099BB209C891529CF7B90C83D9C63D39D989CBB8ECE6DE2B83B/Project1.exe`
Server: www35
Token:
4D7B4D2BFC3F1A9F765A433BA32ED2C5883D0CE133154A0FDB7E7786547A3165DA62393141C4AF8FF36C75222566CF3EB64AF6FBCFC02099BB209C891529CF7B90C83D9C63D39D989CBB8ECE6DE2B83B
You can't just download a file by waiting for the timer to end, and copy the direct link, it's a "token" link. It will only work for a specified period of time before redirecting you back to the download page (which is why you are getting HTML instead of binary data).
Workaround
You will have to download the multiupload's HTML and parse the direct download link from the HTML source code. Only this way provides a sure-fire way of getting an up-to-date token url.
How #Dark Slipstream said, you're attempting to download a file using an expired token url
look how get the new url:
System.Net.WebClient client = new System.Net.WebClient();
// Download URL
Uri uri = new Uri("http://www.multiupload.com/39QMACX7XS");
byte[] dbytes = client.DownloadData(uri);
string responseStr = System.Text.Encoding.ASCII.GetString(dbytes);
HtmlAgilityPack.HtmlDocument doc = new HtmlAgilityPack.HtmlDocument();
doc.LoadHtml(responseStr);
string urlToDownload = doc.DocumentNode.SelectNodes("//a[contains(#href,'files/')]")[0].Attributes["href"].Value;
byte[] data = client.DownloadData(uri);
length = data.Length;
I dont parsing the exceptions

Categories