Click here to Skip to main content
15,906,106 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi,

We are developing a Windows application using Visual Studio 2005 using C#. We have some urgent requirement

Basically we need to read and write a binary (.bin) file in to a memory card(Linear flash). We will connect the memory card using a USB Adapter. The card is detecting in explorer as removable device, but no volumn label details are available.

Using CREATEFILE handle the READ operation is working fine.But the Write operation is not working when i try to write using the CREATEFILE handle. Its it not returning ay errors, but the binary data is not getting changed.

Can anyone tell me how to solve this

Below is the Code which am using for READ and Write

C#
 using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
 
using System.Text;
using System.Windows.Forms;
using System.Management; // need to add System.Management to your project references.

using System.Runtime.InteropServices;
using Microsoft.Win32.SafeHandles;
using System.IO;

namespace GetUSB
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {

        }

        private void Form1_Load(object sender, EventArgs e)
        {
            Console.WriteLine();
            String[] drives = Environment.GetLogicalDrives();
            MessageBox.Show(string.Format("GetLogicalDrives: {0}", String.Join(", ", drives)));

            this.comboBox1.Items.AddRange(new object[] {
            "0",
            "1",
            "2",
            "3",
            "4",
            "5",
            "6"});
        }

        [DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)]
        internal static extern SafeFileHandle CreateFile(string lpFileName,
                    int dwDesiredAccess,
                    int dwShareMode,
                    IntPtr lpSecurityAttributes,
                    uint dwCreationDisposition,
                    uint dwFlagsAndAttributes,
                    SafeFileHandle hTemplateFile);
        internal const int GENERIC_READ = unchecked((int)0x80000000);
        internal const int GENERIC_ALL = unchecked((int)0x10000000);
        internal const int OPEN_EXISTING = 3;
        internal const int FILE_ATTRIBUTE_NORMAL = 0x80;



        protected void ReadRawFile(int DriveNumber)
        {
            const long MAX_FILE_SIZE = 4194304;
            //const long MAX_FILE_SIZE = 1024;
            SafeFileHandle h = null;
            h = CreateFile("\\\\.\\PhysicalDrive" + DriveNumber.ToString(), GENERIC_READ, 0, IntPtr.Zero, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, new SafeFileHandle(IntPtr.Zero, true));
            Cursor.Current = Cursors.WaitCursor;


            if (!h.IsInvalid)
            {
                FileStream stream = new FileStream(h, FileAccess.Read);

                //if (!string.IsNullOrEmpty(sfDialog.FileName))
                //{

                    FileStream outputFile = new FileStream(@"C:\\Temp\\Test" + DriveNumber.ToString() + ".bin", FileMode.Create);
                    //Application.UseWaitCursor = true;
                    //Cursor.Current = Cursors.WaitCursor;
                    Application.DoEvents();
                    try
                    {
                        long LocationCtr = 0;
                        while (LocationCtr < MAX_FILE_SIZE)
                        {
                            //Application.DoEvents();
                            outputFile.WriteByte((byte)stream.ReadByte());
                            LocationCtr++;
                        }
                    }
                    catch (Exception Ex)
                    {
                        MessageBox.Show(Ex.Message);

                    }
                    outputFile.Close();
                    stream.Close();

                    //Cursor.Current = Cursors.Default;
                    Application.DoEvents();

                //}

            }
            else
            {
                // get error code and throw
                int error = Marshal.GetLastWin32Error();

            }
        }



        [DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
        internal static extern int GetLogicalDrives();

        private void button2_Click(object sender, EventArgs e)
        {
            for (int Index = 0; Index < 10; Index++)
            {
                ReadRawFile(Index);//Convert.ToInt32(comboBox1.SelectedValue));
            }
        }

        private void button3_Click(object sender, EventArgs e)
        {
            const long MAX_FILE_SIZE = 4096;
            //const long MAX_FILE_SIZE = 1024;
            SafeFileHandle h = null;
            h = CreateFile("\\\\.\\PhysicalDrive" + "1", GENERIC_ALL, 2, IntPtr.Zero, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, new SafeFileHandle(IntPtr.Zero, true));
            Cursor.Current = Cursors.WaitCursor;



            if (!h.IsInvalid)
            {
                FileStream stream = new FileStream(h, FileAccess.Write);
                FileStream stream1 = new FileStream("C:\\Temp\\Test1.Bin", FileMode.Open);
               
                try
                {
                    char ch = 't';
                    long LocationCtr = 0;
                    while (LocationCtr < MAX_FILE_SIZE)
                    {

                        byte b = Convert.ToByte(ch);// 0;
                        stream.WriteByte(b);// ((byte)stream1.ReadByte());
                        LocationCtr++;
                    }
                }
                catch (Exception Ex)
                {
                    MessageBox.Show(Ex.Message);

                }

            }
            else
            {
                // get error code and throw
                int error = Marshal.GetLastWin32Error();

            }

            h.Close();
            
        }

         

    }


    class USBDeviceInfo
    {
        public USBDeviceInfo(string deviceID, string pnpDeviceID, string description)
        {
            this.DeviceID = deviceID;
            this.PnpDeviceID = pnpDeviceID;
            this.Description = description;
        }
        private string _DeviceID;
        private string _PnpDeviceID;
        private string _Description;
        public string DeviceID { get { return _DeviceID; } set { _DeviceID = value; } }
        public string PnpDeviceID { get { return _PnpDeviceID; } set { _PnpDeviceID = value; } }
        public string Description { get { return _Description; } set { _Description = value; } }
       
    }
}


Regards,
Nidheesh
Posted
Updated 17-Oct-11 23:29pm
v2

1 solution

Think about the restriction to use CREATEFILE. Why not rely on .NET file IO? I found FileStream[^] quite straight forward to use.
C#
// Write to file
using (system.IO.Stream sourceStream = new System.IO.FileStream(source, System.IO.FileMode.Open)
{
    if (sourceStream == null)
        throw new Exception("Cannot open filestream to read from \"" + source + "\".");

    using (System.IO.Stream writeStream = new System.IO.FileStream(path, System.IO.FileMode.OpenOrCreate))
    {
        if (writeStream == null)
            throw new Exception("Cannot open filestream to save to \"" + path + "\".");
    
        byte[] buffer = new byte[stream1.Length];
        stream1.Read(buffer, 0, buffer.Length);
        writeStream.Write(buffer, 0, buffer.Length);
    }
}


[Edit] Now I see, you already know about
FileStream(string, System.IO.FileMode)
 
Share this answer
 
v2
Comments
nidheeshkayal 18-Oct-11 7:06am    
Hi,

Wrote the below code to check. But getting following error message

private void WriteToCard()
{

try
{
using (System.IO.Stream sourceStream = new System.IO.FileStream(@"C:\\Temp\\Test1.bin", System.IO.FileMode.Open))
{
if (sourceStream == null)
{
throw new Exception("Cannot open filestream to read from \"" + "\\\\.\\PhysicalDrive1");
}

using (System.IO.Stream writeStream = new System.IO.FileStream("\\\\.\\PhysicalDrive1", System.IO.FileMode.OpenOrCreate))
{
if (writeStream == null)
{
throw new Exception("Cannot open filestream to save to \"" + "\\\\.\\PhysicalDrive" + "1" + "\".");
}


byte[] buffer = new byte[4096];
sourceStream.Read(buffer, 0, buffer.Length);

writeStream.Write(buffer, 0, buffer.Length);
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}

and the exception is "FileStream will not open 32 bit devices such as disk partitions and tape drives. Avoid the use "\\.\" in teh application"

Thanks
Nidheesh
lukeer 18-Oct-11 7:53am    
First thing I see: in sourceStream's constructor parameter 1, you use '@' in front of a string. You don't need to double the backslashes in this case.

For the exception text: A quick google tells[^] me that \\.\ is some file system notation I have not heard of yet. So if the link doesn't help, you're right where you started. Sorry.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900