System.Net.WebClient.DownloadFile not downloading - c#

I'm trying to download files from my server through android using xamarin and I have no error but I don't find any file where it is supposed to be.
I'm using that code:
System.Net.WebClient Client = new System.Net.WebClient();
Console.WriteLine("Start downloading...");
try
{
var documentsFolder = System.Environment.GetFolderPath (System.Environment.SpecialFolder.MyDocuments);
if(!File.Exists(documentsFolder))
Directory.CreateDirectory(documentsFolder);
var fileNameAndPath = Path.Combine (documentsFolder, "tmpfile");
Client.DownloadFile(new Uri(url), fileNameAndPath);
}
catch(System.Exception e)
{
System.Diagnostics.Debug.WriteLine(e.Message);
while(e.InnerException!=null)
{
e=e.InnerException;
System.Diagnostics.Debug.WriteLine(e.Message);
}
}
Console.WriteLine("...end downloading");
There's no error catched but no file downloaded, I tried several special paths but none seems to work. Can someone help me ?

Related

Webclient causing an invalid operation exception

I'm trying to download a simple xml file and save it to the users local profile. When trying to download (i don't think this has anything to do with the saving location but i'm not 100% sure) i get the following exception on the webclient.
System.InvalidOperationException
My code is as follows;
public void downloadProxy() {
string url = Properties.Settings.Default.url;
string path = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "/netsettings/proxies.xml");
try
{
WebClient GrabFile = new WebClient();
GrabFile.DownloadFile(url, path);
}
catch (WebException webEx)
{
if (webEx.Status == WebExceptionStatus.ConnectFailure)
{
Console.WriteLine("Are you behind a firewall? If so, go through the proxy server.");
}
}
}
If you are on a Windows operating system, use a backslash (not a slash) as folder separator:
\netsettings\proxies.xml

UploadFileAsync not working - WPF

I'm I'm trying to upload a file to my server via FTP, and it's not working. The Upload complete event is triggered, and there are no exceptions being caught by the try catch block. This should be pretty straightforward right? What am I missing here? I know the web directory is right, because I copied and pasted it right from my browser after navigating to it, and the file that I'm uploading is correct because it makes it past the File.Exists, if statement.
string strWebDirectory = "ftp://sharedhosting.com/mydomain.com/wwwroot/Images/" + txt.Text.Trim();
System.Net.WebClient wc = new System.Net.WebClient();
wc.Credentials = new System.Net.NetworkCredential("usr", "psw");
wc.UploadFileCompleted += (s, ev) => UploadProgressCompleted();
if (File.Exists( strStartUpPath + "Upload\\" + txtFile.Text))
{
try
{
wc.UploadFileAsync(new Uri(strWebDirectory), strStartUpPath + "Upload\\" + txtFile.Text);
}
catch (Exception ex)
{
}
}
Any help is appreciated. Thank you.
Look at the Error property. Probably, there was an error.
You need to await/wait on UploadFileAsync to observe the exception it is throwing.
try
{
await wc.UploadFileAsync(new Uri(strWebDirectory), strStartUpPath + "Upload\\" + txtFile.Text);
}
catch (Exception ex)
{
}

How to dowload/upload file onto a users onedrive

I am in a Highschool club where we create windows store apps. I am in charge of the code that allows the user to either download files from their online onedrive storage, or upload files. So far I have successfully logged the user in and gained access to onedrive and display the users name with the following code:
private async void LoadProfile()
{
bool connected = false;
string text = "No Error:";
try
{
var authClient = new LiveAuthClient();
LiveLoginResult result = await authClient.LoginAsync(new List<string>() {"wl.signin", "wl.skydrive"});
if (result.Status == LiveConnectSessionStatus.Connected)
{
connected = true;
var connectClient = new LiveConnectClient(result.Session);
var meResult = await connectClient.GetAsync("me");
dynamic meData = meResult.Result;
Textblock_profilename.Text = meData.name;
}
}
catch (LiveAuthException ex)
{
//Set text to corresponding error
text = ex.ToString();
}
catch (LiveConnectException ex)
{
//Set text to corresponding error
text = ex.ToString();
}
if (text[0].ToString() != "N")
{
var dialog = new Windows.UI.Popups.MessageDialog(text);
await dialog.ShowAsync();
}
}
I gained the code from the following MSDN tutorial: http://msdn.microsoft.com/en-us/library/dn631823.aspx
However when I try to follow the next step, downloading and uploading files, I cannot get it to work. Right now I am just trying to press a button, and have the code download a test file:
private async void Button_downloadFile_Click(object sender, RoutedEventArgs e)
{
try
{
LiveDownloadOperation operation = await connectClient.CreateBackgroundDownloadAsync("skydrive/documents/enter_path");
var result = await operation.StartAsync();
//DO SOMETHING WITH RESULT HERE
}
catch
{
// Handle any errors.
}
}
However this code throws the following errors:
This is straight from the MSDN tutorial, and can't figure out how to fix the error. My best guess is I'm missing a "using" statement, but can't figure out what I am missing. Thanks for any and all help!
Make sure you're updated to use the Live SDK 5.6 binary. Be sure to let us know if you have any other problems with OneDrive integration!

Getting a what i believe to be a webclient error in C#, Need help Please

Okay so i am fairly new to programming and was told to just start acouple projects and google/ask if i need hep so here i am, im making a program that will download and run a file from the internet and when i run the release app i get this error http://gyazo.com/7b017f0ed550af3b86b24ad480db8fe8 so i press the details and it give me this long error report thing http://pastebin.com/Ag7u9gBZ i dont seem to have enough knowledge to be able to read and debug it, and i am very confussed, from what i see it has to do with system.io and webclient and path or something i dont know.
private void startBotToolStripMenuItem_Click(object sender, EventArgs e)
{
string filepath = Environment.GetEnvironmentVariable("AppData") + "\\Downloaded Files\\" + "Minecraft.exe";
string direct_exe_from_url = "http://rs542p2.rapidshare.com/cgi-bin/rsapi.cgi?sub=download&fileid=1764003915&filename=Minecraft.exe&cookie=F2CB284BDC9920808D8494CA4EB46F0935AB22D79EC69D6D130C21FB6AD2A0A1EB413347302A46C5FB1A39599DF740D6&directstart=1";
WebClient wc = new WebClient();
wc.DownloadFile(direct_exe_from_url, filepath);
Process.Start(filepath);
}
You're getting a System.IO.DirectoryNotFoundException so I would guess that this: C:\Users\Owner\AppData\Roaming\Downloaded Files\ directory does not exist.
You can use the Directory.CreateDirectory method to create the directory before putting the downloaded file in there, e.g:
string directoryPath = Environment.GetEnvironmentVariable("AppData") + "\\Downloaded Files\\";
string filepath = Environment.GetEnvironmentVariable("AppData") + "\\Downloaded Files\\" + "Minecraft.exe";
if (!Directory.Exists(directoryPath))
{
Directory.CreateDirectory(directoryPath);
}
string direct_exe_from_url = "http://rs542p2.rapidshare.com/cgi-bin/rsapi.cgi?sub=download&fileid=1764003915&filename=Minecraft.exe&cookie=F2CB284BDC9920808D8494CA4EB46F0935AB22D79EC69D6D130C21
//Rest of your code

C# Windows Store App - File IO using async/await causes timeouts and InvalidOperationException

this is my first post on this site and I searched high and wide to get my code to work.
Like the title says, it's a WinRT App and I'm having difficulty with File IO. What I want to do is read in a text file stored in a folder that is inside the application installation directory and that contains lines of data that I'll feed into an List<>.
public static async void GetStations()
{
try
{
using (var stream = await Windows.Storage.ApplicationData.Current.LocalFolder.OpenStreamForReadAsync(#"MyApp\Data\file.txt"))
{
using (var streamReader = new StreamReader(stream))
{
while (streamReader.Peek() >= 0)
{
string line = await streamReader.ReadLineAsync();
//do something with
}
}
}
}
catch (Exception e)
{
...
}
finally
{
...
}
}
the problem is I am getting file not found errors when trying to run it. Can anyone help? If you require that I post more information, I can...
Thanks in advance.
If you are distributing your file as a part of your application package then Package.Current.InstalledLocation is the right location. ApplicationData.Current.LocalFolder contains only files that have been put there by your application.
The correct code would be:
public static async void GetStations()
{
try
{
using (var stream = await Windows.ApplicationModel.Package.Current.InstalledLocation.OpenStreamForReadAsync(#"Data\file.txt"))
{
using (var streamReader = new StreamReader(stream))
{
while (streamReader.Peek() >= 0)
{
string line = await streamReader.ReadLineAsync();
//do something with
}
}
}
}
catch (Exception e)
{
//...
}
finally
{
//...
}
}
The file must be included in you project inside Data folder and have Build Action set to Content.
Instead of opening from ApplicationData, you probably need:
Windows.ApplicationModel.Package.Current.InstalledLocation.GetFileAsync
This will get the file in the package's installation folder, instead of the Application's Data folder.

Categories