c# - p/Invoke WriteFile fails after 8 writes with access denied -
i using p/invoke c# write directly local hd. drive formatted doesn't contain data. trying write 512 bytes of 0s drive until drive complete full.
the code:
for (double idx = 0; idx < totalsectors; idx++) { file.write(writebuffer, (uint)writebuffer.length); // write buffer int val = pos += (int.parse(bps.tostring()) * int.parse(idx.tostring())); file.movefilepointer(val); application.doevents(); }
as can see iterates process until sectors have been written to. however, reason after 8 iterations receive "access denied" error.
any ideas?
edit xanatos - stupid file position update has been fixed. however, file.movefilepointer() method takes int. casting val (int). method iterates 14 times before throwing "access denied" exception.
edit 2 borrowed code
write method looks this:
public uint write(byte[] buffer, uint cbtowrite) { // returns bytes read uint cbthatwerewritten = 0; if (!writefile(_hfile, buffer, cbtowrite, ref cbthatwerewritten, intptr.zero)) throwlastwin32err(); return cbthatwerewritten; }
and file.movefilepointer method looks this:
public void movefilepointer(int cbtomove, movemethod fmovemethod) { if (_hfile != null) if (setfilepointer(_hfile, cbtomove, intptr.zero, fmovemethod) == invalid_set_file_pointer) throwlastwin32err(); }
int bps = ... // use int! long totalsectors = ... // use long! long pos = 0; // use long! (long idx = 0; idx < totalsectors; idx++) { file.write(writebuffer, (uint)writebuffer.length); // write buffer pos += bps; // file.movefilepointer(pos); // useless, file pointer moved // file.write application.doevents(); }
done! increasing pos
much!
val = pos += (int.parse(bps.tostring()) * int.parse(idx.tostring()));
ignoring val
, , ignoring parse(...tostring)
it's:
pos += bps * idx;
so
idx = 0, pos += 0 (pos = 0), // here it's wrong! initializing twice // same sector! idx = 1, pos += 1 * 512 (pos = 512), idx = 2, pos += 2 * 512 (pos = 1536) wrong!
as sidenote, in .net long
64 bits, big enough number of sectors of hard disk, or size.
Comments
Post a Comment