You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Recently, we have introduced new RandomAccess type (#24847) which exposes some convenient methods for File IO. One of them is RandomAccess.GetLength(SafeFileHandle) that allows for reading file length.
When it comes to setting file length, users can:
use FileMode.Truncate to truncate given file when opening it.
specify preallocationSize to set initial size when opening the file.
The problem is that by using the new APIs, they can't set file length after the file has been opened.
FileStream exposes SetLength method, so should RandomAccess.
voidWriteToFile(stringpath,stringcontents,Encodingencoding){longestimatedFileSize=encoding.GetMaxByteCount(contents.Length);// estimated file lengthusingSafeFileHandlefileHandle=OpenHandle(path,FileMode.Create,FileAccess.Write,preallocationSize:estimatedFileSize);byte[]bytes=encoding.GetBytes(contents);RandomAccess.Write(fileHandle,bytes,fileOffset:0);if(bytes.Length<estimatedFileSize)// shrink the size if initial estimation was wrong{RandomAccess.SetLength(fileHandle,bytes.Length);}}
Oh, I didn't realize this API was missing from RandomAccess until it was too late. I'd just assumed it would be included in a lower-level file operations API set.
What's the best way to work around this in .NET 6 if one always needs to have the possibility of setting the file length available? Open a FileStream, get its SafeFileHandle, use that for reads/writes and call FileStream.SetLength() to set the file length?
Activity
Thealexbarney commentedon Sep 1, 2021
Oh, I didn't realize this API was missing from
RandomAccessuntil it was too late. I'd just assumed it would be included in a lower-level file operations API set.What's the best way to work around this in .NET 6 if one always needs to have the possibility of setting the file length available? Open a
FileStream, get itsSafeFileHandle, use that for reads/writes and callFileStream.SetLength()to set the file length?adamsitnik commentedon Sep 13, 2021
Yes. The alternative it to specify the exact size as
preallocationSizewhen opening filebartonjs commentedon Jan 18, 2022
Video
Looks good as proposed