Необходимо реализовать общение с USB-накопителем (USB 2.0) как с файлом. Точнее скопировать всё содержимое флешки (ввод/вывод). Данный код выдран из MSDN, а функция чтения (ReadFile()) заимствована из книги Агурова "USB.Практика". Имя доступа USB верное (\\?\...).
ReadFile() = 0 GetLastError() = 87 (ERROR_INVALID_PARAMETER/The parameter is incorrect.)
Помогите, чем можете!!!
class FileReader
{
const uint GENERIC_READ = 0x80000000;
const uint OPEN_EXISTING = 3;
System.IntPtr handle;
[System.Runtime.InteropServices.DllImport("kernel32", SetLastError = true)]
static extern unsafe System.IntPtr CreateFile
(
string FileName, // file name
uint DesiredAccess, // access mode
uint ShareMode, // share mode
uint SecurityAttributes, // Security Attributes
uint CreationDisposition, // how to create
uint FlagsAndAttributes, // file attributes
int hTemplateFile // handle to template file
);
[System.Runtime.InteropServices.DllImport("kernel32", SetLastError = true)]
static extern unsafe bool ReadFile
(
System.IntPtr hFile, // handle to file
void* pBuffer, // data buffer
int NumberOfBytesToRead, // number of bytes to read
int* pNumberOfBytesRead, // number of bytes read
int Overlapped // overlapped buffer
);
[System.Runtime.InteropServices.DllImport("kernel32", SetLastError = true)]
static extern unsafe int GetLastError();
[System.Runtime.InteropServices.DllImport("kernel32", SetLastError = true)]
static extern unsafe bool CloseHandle
(
System.IntPtr hObject // handle to object
);
public bool Open(string FileName)
{
// open the existing file for reading
handle = CreateFile
(
FileName,
GENERIC_READ,
0,
0,
OPEN_EXISTING,
0,
0
);
System.Console.WriteLine("handle: {0}", handle);// получает
if (handle != System.IntPtr.Zero)
{
return true;
}
else
{
return false;
}
}
public unsafe int Read(byte[] buffer, int index, int count)
{
int n = 0;
bool s;
fixed (byte* p = buffer)
{
s = ReadFile(handle, p + index, count, &n, 0);
System.Console.WriteLine("ReadFile(): {0} Error: {1}", s, GetLastError()); // ReadFile()=FALSE Error=87
if (!s)
{
return 0;
}
}
return n;
}
public bool Close()
{
return CloseHandle(handle);
}
}
class Test
{
static int Main(string[] args)
{
byte[] buffer = new byte[128];
FileReader fr = new FileReader();
// string name = @"g:\1.txt";
string name = @"\\?\USB#vid_0951&pid_1625#0019e06b07aeb980d0000097#{a5dcbf10-6530-11d2-901f-00c04fb951ed}";
if (fr.Open(name))
{
// Assume that an ASCII file is being read.
System.Text.ASCIIEncoding Encoding = new System.Text.ASCIIEncoding();
int bytesRead;
do
{
bytesRead = fr.Read(buffer, 0, buffer.Length);
string content = Encoding.GetString(buffer, 0, bytesRead);
System.Console.Write("{0}", content);
System.Console.Read();
}
while (bytesRead > 0);
fr.Close();
return 0;
}
else
{
System.Console.WriteLine("Failed to open requested file");
return 1;
}
}
}