Yes - that Jake.
Yes - that Jake.

Reputation: 17121

How do I create a temp file in a directory other than temp?

I've written some code that is supposed to write a file to the temp directory, then copy it to a permanent location, but find that doing so creates a permission-related error on the copy command. The code looks like this:

 string tempPath = Path.GetTempFileName();
 Stream theStream = new FileStream(tempPath, FileMode.Create);

  // Do stuff.

  File.Copy(tempPath, _CMan.SavePath, true);
  File.Delete(tempPath);

I dimly remember that there's an API call I can make to create a temp file in a specified directory, passed as a parameter. But, that's a dim memory from my VB 6 days.

So, how do I create a temp file in a directory other than the temp directory defined by Windows?

Upvotes: 6

Views: 7381

Answers (3)

Patrick McDonald
Patrick McDonald

Reputation: 65421

You can use the GetTempFileName Win32 API Function to do this also:

<DllImport("kernel32.dll")> _
Private Shared Function GetTempFileName(ByVal lpPathName As String, ByVal lpPrefixString As String, ByVal uUnique As Integer, ByVal lpTempFileName As StringBuilder) As Integer

End Function

Sub CreateFile()
    Const path As String = "C:\MyTemp"
    Const prefix As String = "tmp"
    Dim fileName As New StringBuilder(576)
    Dim result As Integer = GetTempFileName(path, prefix, 0, fileName)
End Sub

Upvotes: 3

Moose
Moose

Reputation: 5412

Kinda off base with your question, but maybe you're just not closing the stream before you try to copy it? Seems like you get the permissions-based problem when you open the stream if it's really a permissions problem.

Upvotes: 3

Greg Dean
Greg Dean

Reputation: 30057

Path.Combine(directoryYouWantTheRandomFile, Path.GetRandomFileName())

Upvotes: 18

Related Questions