I searched a little, but could not find something that resolutely solved my problem. I have a code that is a FileStream file from my database and turns into a file on the client machine, which can be viewed in the default application for the file type by double-clicking and downloaded to the client PC when btn is downloaded.
The problem is that when the user double-clicks an item in Listview (for example, mydocument.docx), my code will give it a temporary name and save it in the temp directory on the client machine. But this file is no longer deleted ?! How to get the temporary file that I just created for automatic deletion again, in such cases: 1. The user closes the associated application (for example, Word for .docx), and then deletes the temporary file again. 2. The user closes the Winform window, which deletes the temporary file. 3. All temporary files created by the program will be deleted at the next reboot.
I prefer case 1, but not sure if this is possible.
The source code is as follows:
public void WriteFile(string filePath, StoredFile file, bool tempLocation)
{
byte[] data = file.FilContent.ToArray();
FileStream fileStream;
string tempName = Path.GetRandomFileName(), strPath;
if (tempLocation)
strPath = String.Format(@"{0}{1}{2}", Path.GetTempPath(), tempName, file.FilExt);
else
strPath = String.Format(@"{0}{1}", filePath, file.FilExt);
fileStream = new FileStream(strPath, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.None, 512, FileOptions.DeleteOnClose);
try
{
fileStream.Write(data, 0, data.Length);
fileStream.Flush();
if (tempLocation)
System.Diagnostics.Process.Start(@strPath);
}
finally
{
fileStream.Close();
}
}
... Process.WaitForExit(), , PDF :
. .
FileOptions.DeleteOnClose . , , Process .