亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

在 FileStream 上撤消 DeleteOnClose

在 FileStream 上撤消 DeleteOnClose

C#
慕碼人8056858 2021-10-09 10:02:24
我有一個使用 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));        }        }    }}
查看完整描述

1 回答

?
白衣染霜花

TA貢獻1796條經驗 獲得超10個贊

要直接回答您的問題,不,您不能在中途更改選項。文件流使用 winapi 標志FILE_FLAG_DELETE_ON_CLOSE,這不能在中途更改,它本質上與文件句柄相關聯,當句柄關閉時,操作系統會清理文件,就是這樣,沒有解決方法。

如果您想要不同的行為,則必須事后自己實施。即在其關閉或不關閉后刪除文件。


查看完整回答
反對 回復 2021-10-09
  • 1 回答
  • 0 關注
  • 217 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號