I am trying to read an image file and write it into a new file. But the written image file is not a supported file. please tell me about what is the proper way to read/write image files. Help me!!
Here is my full code. And I did not get any error.
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();
}
}
}
I also used FileStream.Read()
method. But it is also not working for me.
I figured out what was the problem in my code and I fixed my code.
See my fixed code. See what changes I have done.
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();
}