Path.GetRandomFileName vs Path.GetTempFileName

Basis for recommendation https://msdn.microsoft.com/en-us/library/system.io.path.getrandomfilename(v=vs.110).aspx I replaced GetTempFileName with GetRandomFileName to get the name for the temporary file. And this is causing the problem. Sometimes GetRandomFileName returns not the file name, but the location in the System32 folder. And the reason why users without admin rights have the error, file not found. Did I miss something?

Here is the code:

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

;

later when i try to access this file by code:

FileInfo fileInfo = new FileInfo(tempFileName);

      

I have an error:

System.UnauthorizedAccessException: Access denied to path "C: \ Windows \ system32 \ 25ddubwt.qsc".

I realized that when the user launches the program using the menu from Windows / Start, the current directory for the application will be System32

+3


source to share


1 answer


GetTempFileName()

returns full path, GetRandomFileName()

doesn't work.

If you assume you GetRandomFileName()

have a path and write a file to it, it may well end up in System32 if it is the current directory.



To fix, create a full path:

string fname = Path.Combine(Path.GetTempPath(), Path.GetRandomFileName());

      

+2


source







All Articles