gpt4 book ai didi

c# - BinaryWriter 覆盖现有文件 c#

转载 作者:行者123 更新时间:2023-12-04 04:47:27 27 4
gpt4 key购买 nike

要在我的袖珍电脑的内存上写一张图片,我使用以下代码:

pic = (byte[])myPicutureFromDatabase;
using (var fs = new BinaryWriter(new FileStream(filepath, FileMode.Append, FileAccess.Write)))
{
fs.Write(pic);
fs.Flush();
continue;
}

我想问你,如果这个名字的文件已经存在,这个方法是否用新值覆盖文件,或者因为已经存在这个文件而什么都不做?
我需要覆盖该文件,以防该文件已经存在但具有旧值。

最佳答案

来自 MSDN文件模式.创建

Specifies that the operating system should create a new file. If the file already exists, it will be overwritten. This requires FileIOPermissionAccess.Write permission. FileMode.Create is equivalent to requesting that if the file does not exist, use CreateNew; otherwise, use Truncate. If the file already exists but is a hidden file, an UnauthorizedAccessException exception is thrown.



凡是 FileMode.Append

Opens the file if it exists and seeks to the end of the file, or creates a new file. This requires FileIOPermissionAccess.Append permission. FileMode.Append can be used only in conjunction with FileAccess.Write. Trying to seek to a position before the end of the file throws an IOException exception, and any attempt to read fails and throws a NotSupportedException exception.



所以,你应该使用这个
pic = (byte[])myPicutureFromDatabase;
using (var fs = new BinaryWriter(new FileStream(filepath, FileMode.Create, FileAccess.Write)))
{
fs.Write(pic);
fs.Flush();
continue;
}

关于c# - BinaryWriter 覆盖现有文件 c#,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17967509/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com