读取和写入外部驱动器的原始数据

时间:2014-01-29 06:02:54

标签: c# raw-data

我想从驱动器中读取原始数据并将其保存为PC上的文件我还希望能够写回该文件我已经知道修剪空白空间的方法我知道你可以在c ++但是我需要在c#中做,如果可能的话我已经研究过,找不到任何有用的任何帮助非常感谢

P.S。我还在学习c#,这是我试过的代码,但是dk如何修改它才能工作

[DllImport("Kernel32.dll")]

static extern IntPtr CreateFile(string filename,

[MarshalAs(UnmanagedType.U4)]FileAccess fileaccess,

[MarshalAs(UnmanagedType.U4)]FileShare fileshare,

int securityattributes,

[MarshalAs(UnmanagedType.U4)]FileMode creationdisposition,

int flags,

IntPtr template);

static int FILE_FLAG_NO_BUFFERING = 0x20000000; 

static private void Main(string[] args)
{
    IntPtr InvalidHandle = new IntPtr(-1);

    IntPtr ptr = CreateFile(@"\\.\A:",
    //IntPtr ptr = CreateFile(@"\\.F:", // for SD card

    FileAccess.ReadWrite,

    FileShare.ReadWrite,

    0,

    FileMode.OpenOrCreate,

    FILE_FLAG_NO_BUFFERING,

    IntPtr.Zero);

    if (ptr != InvalidHandle)
    {

        try
        {
            //FileStream disk = new FileStream(ptr, FileAccess.ReadWrite); // doesn't work as well
            FileStream disk = new FileStream(new Microsoft.Win32.SafeHandles.SafeFileHandle(ptr, true), FileAccess.ReadWrite);
            Console.WriteLine(disk.CanRead);
            Console.WriteLine(disk.CanSeek);
            Console.WriteLine(disk.CanTimeout);
            Console.WriteLine(disk.CanWrite); // always false

            byte[] inBuffer = new byte[512];
            var x = new byte[] { 1 };
            disk.Write(x, 0, 1); // error
            disk.Read(inBuffer, 0, 1);

            for (int i = 0; i < 2; i++)

                Console.Write("{0,4}", inBuffer[i]);

            Console.ReadLine();         
        }
        catch (Exception e)
        {
            Console.WriteLine(e.ToString());
            Console.ReadLine();
        }
    }

}

0 个答案:

没有答案