Reputation: 17121
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
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
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
Reputation: 30057
Path.Combine(directoryYouWantTheRandomFile, Path.GetRandomFileName())
Upvotes: 18