C# 在同一文件流上读写
我正在尝试使用将文件夹中的所有PNG转换为8bpp PNG。我尝试使用以下代码:C# 在同一文件流上读写,c#,filestream,overwrite,C#,Filestream,Overwrite,我正在尝试使用将文件夹中的所有PNG转换为8bpp PNG。我尝试使用以下代码: foreach (string file in Directory.GetFiles(tempFolderPath, "*.png", SearchOption.TopDirectoryOnly)) { using (MemoryStream memory = new MemoryStream()) { using (F
foreach (string file in Directory.GetFiles(tempFolderPath, "*.png", SearchOption.TopDirectoryOnly))
{
using (MemoryStream memory = new MemoryStream())
{
using (FileStream fs = new FileStream(file, FileMode.OpenOrCreate, FileAccess.ReadWrite))
{
using (Bitmap image = new Bitmap(fs))
{
using (Image quantized = quantizer.QuantizeImage(image))
{
quantized.Save(memory, ImageFormat.Png);
byte[] bytes = memory.ToArray();
fs.Write(bytes, 0, bytes.Length);
}
}
}
}
}
然而,这不起作用。没有例外。只是不写入文件。我已经用这个工作代码替换了它
Bitmap image;
foreach (string file in Directory.GetFiles(tempFolderPath, "*.png", SearchOption.TopDirectoryOnly))
{
using (FileStream fso = new FileStream(file, FileMode.Open, FileAccess.ReadWrite))
{
image = new Bitmap(fso);
}
using (MemoryStream memory = new MemoryStream())
{
using (FileStream fs = new FileStream(file, FileMode.Create, FileAccess.ReadWrite))
{
using (Image quantized = quantizer.QuantizeImage(image))
{
quantized.Save(memory, ImageFormat.Png);
byte[] bytes = memory.ToArray();
fs.Write(bytes, 0, bytes.Length);
}
}
}
}
似乎是FileMode。OpenOrCreate
可以执行其中一种操作,但不能同时执行这两种操作
在同一
文件流上是否还有读写操作?您的代码只是将这些图像的内容连接到一个文件,因为您没有重置文件流中的位置
但是使用一个流是个坏主意。如果您的新文件比旧文件小,则结果将被破坏,因为文件大小不会调整为更小
改为使用临时文件。在下面的C#Stackoverflow上进行快速谷歌搜索,读取和写入相同的文件流
@MethodMan是的,我找到了,我使用了最上面的答案。我还找到并尝试添加fs.Flush(),但也没有成功。