Path.GetRandomFileName与Path.GetTempFileName

Gen*_*Ziy 4 c#

Base on recommendation from https://msdn.microsoft.com/en-us/library/system.io.path.getrandomfilename(v=vs.110).aspx I have replaced GetTempFileName with GetRandomFileName to get a name for the temp file. And it cause a problem. Sometimes GetRandomFileName return not a file name but location in System32 folder. And of cause users with no admin rights are having an error that file is not found. Do I missed anything?

Here is a code:

string tempFileName = Path.GetRandomFileName(); FileStream tempFileStream = null; tempFileStream = File.Open(tempFileName, FileMode.Create, FileAccess.ReadWrite);

later on when I try to access that file by code:

FileInfo fileInfo = new FileInfo(tempFileName);
Run Code Online (Sandbox Code Playgroud)

I have an error:

System.UnauthorizedAccessException: Access to the path 'C:\Windows\system32\25ddubwt.qsc' is denied.

I realised that when user initiate a program by using menu from Windows/Start button current directory for the application will be System32

Ale*_* K. 5

GetTempFileName()返回完整路径,GetRandomFileName()不返回。

如果您假设GetRandomFileName()有一个路径并写入该路径,则该文件很可能会在System32中以当前目录结尾。

要修复,请创建完整路径:

string fname = Path.Combine(Path.GetTempPath(), Path.GetRandomFileName());
Run Code Online (Sandbox Code Playgroud)

  • 明确提及“GetRandomFileName()”不会在磁盘上创建文件,而“GetTempFileName()”会创建文件,这可能是个好主意。 (4认同)
  • 一个会指向 c:\something\temp\ 另一个不会,这是唯一的区别,而且是一个很大的区别。其他东西可能会更改目录 - 这就是为什么您应该尽可能指定绝对路径的原因。 (2认同)
  • 最好不要假定当前目录的位置,因为有很多原因可能会导致当前目录发生更改,例如本[SO问题](http://stackoverflow.com/questions/930816/why-请执行openfile对话框更改我的工作目录) (2认同)