-
Notifications
You must be signed in to change notification settings - Fork 4.8k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
[API Proposal]: Introduce RandomAccess.SetLength(SafeFileHandle handle) method #58376
Comments
Tagging subscribers to this area: @dotnet/area-system-io Issue DetailsBackground and motivationRecently, we have introduced new When it comes to setting file length, users can:
The problem is that by using the new APIs, they can't set file length after the file has been opened.
API Proposalnamespace System.IO
{
public static class RandomAccess
{
public static void SetLength(SafeFileHandle handle, long length);
}
} API Usagevoid WriteToFile(string path, string contents, Encoding encoding)
{
long estimatedFileSize = encoding.GetMaxByteCount(contents.Length); // estimated file length
using SafeFileHandle fileHandle = 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);
}
} RisksI can't see any.
|
Oh, I didn't realize this API was missing from 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 |
Yes. The alternative it to specify the exact size as |
Looks good as proposed namespace System.IO
{
public partial static class RandomAccess
{
public static void SetLength(SafeFileHandle handle, long length);
}
} |
Background and motivation
Recently, we have introduced new
RandomAccess
type (#24847) which exposes some convenient methods for File IO. One of them isRandomAccess.GetLength(SafeFileHandle)
that allows for reading file length.When it comes to setting file length, users can:
FileMode.Truncate
to truncate given file when opening it.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
exposesSetLength
method, so shouldRandomAccess
.API Proposal
API Usage
Risks
I can't see any.
The text was updated successfully, but these errors were encountered: