10

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);

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

GenZiy
  • 1,427
  • 2
  • 15
  • 20
  • Any example of a location being returned instead of a filename? – Mike Cheel Mar 29 '17 at 15:54
  • Here is a C# Fiddle demonstrating what Alex K is saying. Notice it only prints a random filename: https://dotnetfiddle.net/dqKbUy Also, GetRandomFileName() doesn't create a file while GetTempFileName creates a zero byte file and returns the full path to it. – Mike Cheel Mar 29 '17 at 15:55
  • I have to edit my question. If you initiate your exe by using sortcut on Windows Start button menu current directory became System32. – GenZiy Mar 30 '17 at 19:49

1 Answers1

15

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());
Alex K.
  • 171,639
  • 30
  • 264
  • 288
  • 1
    It would be a reasonable explanation. But it is not a current directory. and it is happening only 10-25% of the time. – GenZiy Mar 29 '17 at 16:07
  • 1
    One will point to c:\something\temp\ the other will not, thats the only difference and its quite a big one. Something else may be changing the directory - which is why you should always specify an absolute path where possible. – Alex K. Mar 29 '17 at 16:12
  • Does it mean that sometimes current directory can be System32 and sometimes not? Depends on what? – GenZiy Mar 29 '17 at 16:15
  • 2
    It's best to not assume the location of current directory, being there are any number of reasons why the current directory might change for example OpenFileDialog as discussed in this [SO question](http://stackoverflow.com/questions/930816/why-does-openfiledialog-change-my-working-directory) – RamblinRose Mar 29 '17 at 16:56
  • 3
    It may be a good idea to explicitly mention that `GetRandomFileName()` does not create the file on disk while `GetTempFileName()` does it. – AlinG May 13 '21 at 18:23