如何在c#中使用FileStream读取和写入.img文件?
我正在尝试读取图像文件并将其写入新文件。但写入的图像文件不是受支持的文件。请告诉我什么是读取/写入图像文件的正确方法。救救我 这是我的全部代码。 我没有得到任何错误如何在c#中使用FileStream读取和写入.img文件?,c#,filestream,read-write,C#,Filestream,Read Write,我正在尝试读取图像文件并将其写入新文件。但写入的图像文件不是受支持的文件。请告诉我什么是读取/写入图像文件的正确方法。救救我 这是我的全部代码。 我没有得到任何错误 using System; using System.IO; namespace readfile { class Program { static int totalbyte = 0; static void Main(string[] args) {
using System;
using System.IO;
namespace readfile
{
class Program
{
static int totalbyte = 0;
static void Main(string[] args)
{
string path = "C:/Users/Nitesh Rathi/Downloads/"; // file's path.
string filename = "IMG_20200317_150302.jpg"; // file's name.
string fullpath = path + filename;
readfile(fullpath);
writefile(filename);
Console.ReadKey(false);
}
static void readfile(string path)
{
FileStream stm = File.Open(path, FileMode.Open); // open a file using filestream.
int size = (int)stm.Length; // size of the file.
byte[] data = new byte[stm.Length]; // file buffer.
while (size > 0) // loop until file' size is not 0.
{
int read = stm.ReadByte(); // reading file's data.
size -= read;
totalbyte += read;
}
}
static void writefile(string filename)
{
FileStream stm = File.Create(filename); // create a new file.
byte[] data = new byte[totalbyte]; // file's data.
Console.WriteLine("Writing data into file...");
stm.Write(data, 0, data.Length); // writing data into created file.
Console.WriteLine("data has been wrote into file.");
stm.Close();
}
}
}
我还使用了
FileStream.Read()
方法。但它对我也不起作用。我发现了代码中的问题所在,并修复了代码
查看我的固定代码。看看我做了什么改变
Public static byte[] data; // this variable will be store file's content.
static void readfile(string path)
{
FileStream stm = File.Open(path, FileMode.Open); // open a file using filestream.
int size = (int)stm.Length; // size of the file.
data = new byte[size];
while (size > 0) // loop until file' size is not 0.
{
int read = stm.read(data, totalbyte, size); // reading file's data.
size -= read;
totalbyte += read;
}
}
static void writefile(string filename)
{
FileStream stm = File.Create(filename); // create a new file.
byte[] bytes = data;
Console.WriteLine("Writing data into file...");
stm.Write(data, 0, data.Length); // writing data into created file.
Console.WriteLine("data has been wrote into file.");
stm.Close();
}
您的目标只是“复制”现有文件吗?如果是这样的话,您可以简单地使用该方法,而不是自己构建它。您正在向文件中写入所有零,因为您只需要执行新字节[totalbyte]。关闭前,执行stm.Flush()@jdweng你能告诉我正确的方法是什么吗?试试
System.IO.File.Copy(完整路径,文件名)代码>即使修复了,您的代码也试图以非常低效的方式逐字节复制文件,并将所有文件加载到内存中。请不要这样做。您的解决方案只需一个File.Copy
命令即可。此代码不必要地复杂,可以简化为两行:static void ReadFile(string path){data=File.ReadAllBytes(path);}
和static void WriteFile(string path){File.writealbytes(path,data);}
。因此,实际上根本不需要这些方法,因为它们与内置功能一样。