On my application i have a Config-FileReader - These checks on Startup, if a Temp
directory (on applications folder, here the configuration will be stored as Config.json
) exists, otherwise the application will create it. These steps works for a long time correctly.
After few days development, i had today create a simple File-Downloader:
public static void Download(string url, string destination, Callback OnSuccess) {
System.Diagnostics.Debug.WriteLine("[Download] " + url + " to " + destination + " (" + Utils.getFileName(url) + ")");
using (var client = new WebClient())
{
client.Headers[HttpRequestHeader.UserAgent] = Software.getName() + "/" + Software.getVersion() + " (" + Software.getOSVersion() + "; " + Software.getOSBit() + "; " + Software.getOSVersionFull() + ")";
client.DownloadDataCompleted += (s, e) =>
{
var text = e.Result;
File.WriteAllText(destination, Path.Combine(destination, Utils.getFileName(url)));
OnSuccess((Object) Path.Combine(destination, Utils.getFileName(url)));
};
client.DownloadDataAsync(new Uri(url));
}
}
When i try to download a file to the previous created Temp
directory, an UnauthorizedAccessException
comes up. Curiously is: The directory was created successfully by the application and the config file will be created/readed/writed.
But when i try to download a file:
API.Download(media.URL, Software.getPath() + "Temp", OnSuccess);
Debug-Output of the Downloader:
[Download] https://c-ash.smule.com/sf/s26/arr/88/4e/48afbe6c-9aeb-4cc7-82cf-e04d5f0d6b44.mp3 to C:\Users\info\Documents\SharpDevelop Projects\SongManager\SongManager\bin\Debug\Temp (48afbe6c-9aeb-4cc7-82cf-e04d5f0d6b44.mp3)
i't gives an UnauthorizedAccessException
:
System.UnauthorizedAccessException: Access to the Path "C:\Users\info\Documents\SharpDevelop Projects\SongManager\SongManager\bin\Debug\Temp" was denied.
Edit
The same problem appears, when i use another directory, which will created live before the download starts.
Edit 2
My second thinks are, thats an Threading problem, because DownloadDataAsync
running on another thread. But an
Application.Current.Dispatcher.Invoke(DispatcherPriority.Background, new ThreadStart(delegate {
File.WriteAllText(destination, Path.Combine(destination, Utils.getFileName(url)));
}));
won't fix the problem.
I call shenanigans
File.WriteAllText Method (String, String)
Parameters
path
- Type: System.String
- The file to write to.
contents
- Type: System.String
- The string to write to the file.
Your Code
client.DownloadDataCompleted += (s, e) =>
{
var text = e.Result;
// look at your parameters
File.WriteAllText(destination, Path.Combine(destination, Utils.getFileName(url)));
OnSuccess((Object)Path.Combine(destination, Utils.getFileName(url)));
};
You are calling File.WriteAllText
on a directory, and passing the combined path as the contents.
The error should be,
"Step away from the keyboard young jedi and make your self a coffee! A directory is not a file and you have no business writing to one"