Re: C#, CreateFile and FileStream = Invalid Handler




"Adam W" <adamwortmann@xxxxxxxxx> wrote in message news:1128233860.497854.140100@xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
Hi Gurus,

I've been playing with this C# code for 2 days and Googling like a Mad
Code Monkey.  I hope you can help.

I'm working on a program that can read and write bits on the Floppy
Drive (A).   The overall goal is to read/write blocks (512 bytes).
However, my CreateFile function is bringing back a -1, Invalid Handler.
Therefore, when I pass it open a FileStream, all heck breaks loose.

I'm Using:

using System;
using System.IO;
using System.Runtime.InteropServices;

I've also brought in:

[DllImport("Kernel32.dll")]
static extern IntPtr CreateFile(string filename,
[MarshalAs(UnmanagedType.U4)]FileAccess fileaccess,


euh, what makes you thinkm that the FileAccess enum, is compatible with the flags that are given for The win32 equivalent?
I might be wrong, but I am very suspicious about this.


Success

[MarshalAs(UnmanagedType.U4)]FileShare fileshare,
int securityattributes,
[MarshalAs(UnmanagedType.U4)]FileMode creationdisposition,
int flags,
IntPtr template);
static int FILE_FLAG_NO_BUFFERING = 0x20000000;

Now for the Code:

public void test()
{
IntPtr ptr = CreateFile("\\\\.\\A:",
FileAccess.ReadWrite,
FileShare.ReadWrite,
0,
FileMode.OpenOrCreate,
FILE_FLAG_NO_BUFFERING,
IntPtr.Zero);

FileStream disk = new FileStream(ptr, FileAccess.ReadWrite);

byte[] outBuffer = new byte[512];
byte[] inBuffer = new byte[512];

outBuffer[0] = 1;
outBuffer[1] = 0;
outBuffer[2] = 1;

disk.Seek(0, SeekOrigin.Begin);
for (int i=0; i<512; i++)
{
disk.WriteByte(outBuffer[i]);
}

disk.Seek(0, SeekOrigin.Begin);
for (int i=0; i<512; i++)
{
inBuffer[i] = (byte) disk.ReadByte();
}
for (int i=0; i<20; i++)
{
Console.Write(inBuffer[i]);
}
Console.WriteLine();



}

I really like C#.  I can make this work in C++, but I really don't want
to port the rest over.  Thanks so much for your help.

Adam


.