File.open()有一个例外"客户端没有持有所需的特权"

时间:2014-08-27 19:21:36

标签: c# exception io

以下代码来自教科书:

namespace FileStreamApp
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("***** Fun with FileStreams *****\n");
            using (FileStream fStream = File.Open(@"C:\myMessage.dat", FileMode.Create))
            {

                string msg = "Hello!";
                byte[] msgAsByteArray = Encoding.Default.GetBytes(msg);

                fStream.Write(msgAsByteArray, 0, msgAsByteArray.Length);
                // Reset internal position of stream. 
                fStream.Position = 0;

                Console.Write("Your message as an array of bytes: ");
                byte[] bytesFromFile = new byte[msgAsByteArray.Length];
                for (int i = 0; i < msgAsByteArray.Length; i++)
                {
                    bytesFromFile[i] = (byte)fStream.ReadByte();
                    Console.Write(bytesFromFile[i]);
                }
                // Display decoded messages. 
                Console.Write("\nDecoded Message: ");
                Console.WriteLine(Encoding.Default.GetString(bytesFromFile));
            }
            Console.ReadLine();
        }
    }
}

但是当我运行它时,我遇到了运行时错误。我无法弄明白。错误说:

 System.IO.IOException was unhandled
 HResult=-2147023582
 Message=A required privilege is not held by the client.

 Source=mscorlib
 StackTrace:
   at System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath)
   at System.IO.FileStream.Init(String path, FileMode mode, FileAccess access, Int32       
   rights, Boolean useRights, FileShare share, Int32 bufferSize, FileOptions options,    
   SECURITY_ATTRIBUTES secAttrs, String msgPath, Boolean bFromProxy, Boolean 
   useLongPath, Boolean checkHost)
   at System.IO.FileStream..ctor(String path, FileMode mode, FileAccess access,   
   FileShare share)
   at System.IO.File.Open(String path, FileMode mode)
   at FileStreamApp.Program.Main(String[] args) in   
   C:\MyVSExamples\FileStreamApp\Program.cs:line 15
   at System.AppDomain._nExecuteAssembly(RuntimeAssembly assembly, String[] args)
   at System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, 
   String[] args)
   at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
   at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
   at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, 
   ContextCallback callback, Object state, Boolean preserveSyncCtx)
   at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, 
   ContextCallback callback, Object state, Boolean preserveSyncCtx)
   at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, 
   ContextCallback callback, Object state)
   at System.Threading.ThreadHelper.ThreadStart()

   InnerException: 

1 个答案:

答案 0 :(得分:0)

尝试使用其他路径。看起来你没有c的写权限:这是正常的。尝试使用类似c:\ temp的内容。