我有一個使用 FileOption:DeleteOnClose 在內部使用 FileStream 的類。正常行為是當我為類分配文件名時,我不使用 DeleteOnClose,否則我使用它。唯一的問題是我有時需要撤消DeleteOnClose。我在這里解釋更深的細節會太長。當然,我可以創建一個副本并將已使用 DeleteOnClose 打開的 FileStream 的內容復制到另一個 FileStream,但文件大小太大(> = 30GB),因此這種方法是不切實際的。手動刪除文件不起作用,因為這些類或多或少用作需要由 GC 處理的內存容器。此外,當發生某些事情時,放置死文件也無濟于事。所以我希望是否有辦法撤消 DeleteOnClose 屬性,因為這可以完成,例如使用 SetFileAttributes,例如可以設置/取消設置臨時標志。根據 TheGeneral 和 TonPlooij 的評論,我創建了一個小示例來測試 FileDispositionInfo,但不知何故這也不起作用(從http://source.roslyn.codeplex.com/#Roslyn.Test.Utilities/TempFiles/DisposableFile復制。 cs,4d5c94058d1b4cd3):using Microsoft.Win32.SafeHandles;using System;using System.IO;using System.Runtime.InteropServices;namespace ConsoleApp11{ class Program { [DllImport("kernel32.dll", PreserveSig = false)] private static extern void SetFileInformationByHandle(SafeFileHandle handle, int fileInformationClass, ref uint fileDispositionInfoDeleteFile, int bufferSize); private const int FileDispositionInfo = 4; internal static void PrepareDeleteOnCloseStreamForDisposal(FileStream stream) { // tomat: Set disposition to "delete" on the stream, so to avoid ForeFront EndPoint // Protection driver scanning the file. Note that after calling this on a file that's open with DeleteOnClose, // the file can't be opened again, not even by the same process. uint trueValue = 1; SetFileInformationByHandle(stream.SafeFileHandle, FileDispositionInfo, ref trueValue, sizeof(uint)); } } }}
在 FileStream 上撤消 DeleteOnClose
慕碼人8056858
2021-10-09 10:02:24