繁体   English   中英

如何在c#中使用FileStream读写.img文件?

[英]How to read and write .img files using FileStream in c#?

我正在尝试读取图像文件并将其写入新文件。 但写入的图像文件不是受支持的文件。 请告诉我读/写图像文件的正确方法是什么。 帮我!!

这是我的完整代码。 我没有收到任何错误。

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();
    }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM