How to create a temporary file in a directory other than temp?

I wrote code that should write the file to the temp directory, and then copy it to a permanent location, but find that this creates a copy rights error. The code is as follows:

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

  // Do stuff.

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

I vaguely remember that there is an API call that I can create to create a temporary file in the specified directory, passed as a parameter. But, what a dull memory from my VB 6 days.

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

+3
source share
3 answers
Path.Combine(directoryYouWantTheRandomFile, Path.GetRandomFileName())
+12
source

You can also use the GetTempFileName Win32 API function:

<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
+3

Reset the database with your question, but maybe you just do not close the stream before trying to copy it? It looks like you are getting a permission problem when opening a stream, if it really is a permission problem.

+2
source

Source: https://habr.com/ru/post/1705193/


All Articles