Path. Getrandomfilename vs Path. Gettempfilename

Path. Getrandomfilename vs Path. Gettempfilename

Base on recommendation from (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);

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

3

1 Answer

GetTempFileName() returns a full path, GetRandomFileName() does not.

If you assume GetRandomFileName() has a path and write to it the file may well end up in System32 if thats the current directory.

To fix create a full path:

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Robert Thorne
Author

Robert Thorne

Robert Thorne covers electric vehicle innovations, autonomous driving systems, global mobility trends, and automotive engineering developments.