简体   繁体   中英

C# UnauthorizedAccessException error

I am transfering files through sockets. When I try to save files to a custom directory, I get this error using BinaryWrite function.

private void downloadFromServer()
{
   try
   {
      byte[] buffer = new byte[5000 * 1024];
      byte[] incomingFile = new byte[5000 * 1024];
      buffer = Encoding.Default.GetBytes(getUserName.Text + "Download" 
         + getFileName.Text + "end");
      clientSocket.Send(buffer);
      activityLog.AppendText("Preparing to download... \n");
      while (incomingFile != null)
      {
         clientSocket.Receive(incomingFile);

         int receivedBytesLen = incomingFile.Length;
         int fileNameLen = BitConverter.ToInt32(incomingFile, 0);
         File.WriteAllBytes(fileDir, incomingFile);
      } 
      activityLog.AppendText("File saved to " + fileDir + "\n");
   }
   catch (Exception ex)
   {
      MessageBox.Show(ex.Message);
   }
}

File.WriteAllBytes(fileDir, incomingFile); requires file name. From variable name it looks like you are using folder name. Ie should be @"e:\\tempfile.bin" instead of @"e:\\" .

File.WriteAllBytes

Given a byte array and a file path , this method opens the specified file, writes the contents of the byte array to the file, and then closes the file.

Note if fileDir means file name than you should looks for other not-so-truthful names throughout your code...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM