Is it possible 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.
Asked
Active
Viewed 2,880 times
2
-
http://msdn.microsoft.com/en-us/library/system.io.filestream.filestream.aspx – Dave Sep 28 '11 at 07:14
4 Answers
0
You can use FileOptions.DeleteOnClose
as one of parameters. File will be automatically removed after you finish your operations and dispose a stream.

Sergei B.
- 3,227
- 19
- 18
-
I am developing File Queue system and I use FileAttributes.Temporary as special attribute for queue actions. So when file is created for file streaming I would like to assign FileAttributes.Temporary imidiatlly. – Tomas Sep 28 '11 at 07:18
-
Just look through overloads and you'll answer your question by yourself - There is no overload to set FileAttributes immediately. You could create an extension method if you want to do it in a one line, so you'll be able to use `using` construct and dispose the stream properly without using try..finally. So, why do you need it in a one line? – Sergei B. Sep 28 '11 at 07:34
-1
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

Frederik Gheysels
- 56,135
- 11
- 101
- 154
-1
Ya, surely you can apply FileAttributes also by using File.SetAttributes
Method

Sai Kalyan Kumar Akshinthala
- 11,704
- 8
- 43
- 67
-
I want to do that at the same time when FileStream create the file. Does FileStream method has any possibilities to set FileAttributes? – Tomas Sep 28 '11 at 07:13
-1
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

Isak Savo
- 34,957
- 11
- 60
- 92