create file with FileStream and apply FileAttributes
Is it po开发者_运维问答ssible while creating the file with FileStream also apply FileAttributes at the same time? I would like to create file for stream writing with FileAttributes.Temporary file attribute.
You can use FileOptions.DeleteOnClose
as one of parameters. File will be automatically removed after you finish your operations and dispose a stream.
Ya, surely you can apply FileAttributes also by using File.SetAttributes
Method
Why do you need to do it all at once?
- Just create the file (using File.Create or, if its a temporary file, use GetTempFileName.)
- Set the attributes on the newly created file
- Open the file using whatever method suits you
You can do this if you use the Win32 CreateFile method
uint readAccess = 0x00000001;
uint writeAccess = 0x00000002;
uint readShare = 0x00000001;
uint createAlways = 2;
uint tempAttribute = 0x100;
uint deleteOnClose = 0x04000000;
new FileStream(new SafeFileHandle(NativeMethods.CreateFile("filename",
readAccess | writeAccess,
readShare,
IntPtr.Zero,
createAlways,
tempAttribute | deleteOnClose,
IntPtr.Zero),
true),
FileAccess.ReadWrite, 4096, true);
private static class NativeMethods
{
[DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
internal static extern IntPtr CreateFile(string name, uint accessMode, uint shareMode, IntPtr security, uint createMode, uint flags, IntPtr template);
}
For more information, see the MSDN documentation of CreateFile
精彩评论