0

I am trying to create a new jpeg file from an async task. The relevent code snippet is shown below

private async void OnSocketConnectionReceived(StreamSocketListener sender, StreamSocketListenerConnectionReceivedEventArgs args)
{
   await ReceiveFile(args);
}

private async Task ReceiveFile(StreamSocketListenerConnectionReceivedEventArgs args)
{
  string pathString = @"C:\Users\sarav\test.jpg";
  FileStream writeStream = new FileStream(pathString, FileMode.CreateNew, FileAccess.Write, FileShare.None, bufferSize: 4096, useAsync: true);
}

It throws the System.UnauthorizedAccessException above in FileStream. The same Filestream snippet for the same path is working on a console based C# application, in the sense the file test.jpg is getting created. Any suggestions as of what i am missing here.

1 Answers1

0

Most likely you are trying to create a file under different user. See what you have in the Thread.CurrentPrincipal in both scenarios before you do new FileStream.

Since you don't have an exact code and environment setup in the question, I cannot propose an exact solution, but can give a direction to dig into. If you have a different user, just make sure that it has an access to particular directory you need.

Serge Semenov
  • 9,232
  • 3
  • 23
  • 24
  • I am logged into my windows 10 laptop using my gmail account, which has admin privileges. Shouldnt that be fine? – Saravanan Jayakumar Sep 17 '16 at 18:51
  • Also regarding Thread.CurrentPrincipal, i am watching this in my debugger. Can you please tell me which field int hat structure i need to look for? – Saravanan Jayakumar Sep 17 '16 at 19:12
  • You can look at `System.Security.Principal.WindowsIdentity.GetCurrent()` to see which Windows user you are running under. – Serge Semenov Sep 17 '16 at 20:18
  • I am unable to view any of these variables since i guess its an asynchronous task?. The debugger shows as not foudn with red cross marks. Also one more observation if i try to create the file from the UI thread context, then i get a different exception "Synchronous operations should not be performed on the UI thread. Consider wrapping this method in Task.Run." – Saravanan Jayakumar Sep 17 '16 at 20:35
  • If i put it in this code block i get Synchronous operations should not be performed on the UI thread var task = Dispatcher.RunAsync(CoreDispatcherPriority.Normal, async () => { await ReceiveFile(args); }); – Saravanan Jayakumar Sep 17 '16 at 20:38
  • I feel the issue is since i am trying to create the file from a callback handler, the handler doesn't have any user credential context hence the permission issue. Is there a a solution to this, since i need to create the file once i get the socket call back called – Saravanan Jayakumar Sep 17 '16 at 21:14