简体   繁体   English

C#UnauthorizedAccessException错误

[英]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. 当我尝试将文件保存到自定义目录时,使用BinaryWrite函数出现此错误。

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:\\" . 即应该是@"e:\\tempfile.bin"而不是@"e:\\"

File.WriteAllBytes 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... 请注意,如果fileDir意味着文件名,那么您应该在整个代码中寻找其他不太真实的名称...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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