When attempting to download and write a file as a local user (ie, not run as admin), the following code is throwing an UnauthorizedAccessException(Access to the path is denied.). Originally, I assumed that this was due to the application attempting to write files directly to the C drive. However, I get the same error when attempting to save files to the local user's documents drive, as gotten by this:
Environment.GetFolderPath(Environment.SpecialFolder.Personal);
private bool DownloadFile(Stream srcStream, string dstFile)
{
bool success = false;
byte[] buffer = new byte[16384];
int byteCount;
FileStream destStream = null;
try
{
destStream = File.Create(dstFile);
while ((byteCount = srcStream.Read(buffer, 0, 16384)) != 0)
{
destStream.Write(buffer, 0, byteCount);
}
success = true;
}
catch(Exception)
{
return success;
}
finally
{
try { destStream.Close(); }
catch (Exception) { }
}
return success;
}
Ok I just did a unit test with your code.
The problem is
destStream = File.Create(dstFile);
This is a folder not a file!
try this:
destStream = File.Create(dstFile + "\Test.txt");
And tadaaaaa. No more exception ;)
You can not write into a folder. only inside file.
and please use using() when needed :)
Unit test:
[TestMethod]
public void TestMethod1()
{
var path = Environment.GetFold`enter code here`erPath(Environment.SpecialFolder.Personal);
// path = "C:\Users\pix\Documents"
using (var memoryStream = new MemoryStream())
{
var result = DownloadFile(memoryStream, path);
Assert.IsFalse(result);
result = DownloadFile(memoryStream, Path.Combine("FILE.txt"));
Assert.IsTrue(result);
}
}
private bool DownloadFile(Stream srcStream, string dstFile)
{
bool success = false;
byte[] buffer = new byte[16384];
int byteCount;
FileStream destStream = null;
try
{
destStream = File.Create(dstFile);
while ((byteCount = srcStream.Read(buffer, 0, 16384)) != 0)
{
destStream.Write(buffer, 0, byteCount);
}
success = true;
}
catch (Exception ex)
{
return success;
}
finally
{
try { destStream.Close(); }
catch (Exception) { }
}
return success;
}