Click here to Skip to main content
15,881,882 members
Please Sign up or sign in to vote.
5.00/5 (1 vote)
See more:
Hi guys,

I am trying to use windows API writefile in c#.
my problem is after I write something to the file, it does not increase the file pointer and so if I write something else it rewrite it!!
C#
[DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Auto)]
public static extern IntPtr CreateFile(
    string lpFileName,
    uint dwDesiredAccess,
    uint dwShareMode,
    IntPtr lpSecurityAttributes,
    uint dwCreationDisposition,
    uint dwFlagsAndAttributes,
    IntPtr hTemplateFile);

[DllImport("kernel32.dll", BestFitMapping = true, CharSet = CharSet.Ansi)]
public static extern bool WriteFile(
    IntPtr hFile,
    System.Text.StringBuilder lpBuffer,
    uint nNumberOfBytesToWrite,
    out uint lpNumberOfBytesWritten,
    [In] ref System.Threading.NativeOverlapped lpOverlapped);

_FileHandle = CreateFile(_CSVFileName, 0x40000000, 0x00000001, IntPtr.Zero, 4, 0x00000080, IntPtr.Zero);

WriteFile(_FileHandle, oSTR, LenToWrite, out LenWritten, ref OverLap);

For some reasons I do not want to use system.IO.*
(I have a problem using system.io.* -my previous question- )

what am I doing wrong?!

Thanks.

re-tagged as c# only.
-Emilio-
Posted
Updated 1-Nov-10 21:46pm
v3
Comments
Nish Nishant 1-Nov-10 20:51pm    
I don't think your previous problem was a .NET bug, so I am a little surprised that you decided to go this way. That said, it does suite you that P/Invoking the API has solved your problem, but if I were you I'd stay alert to potential issues cropping up because I feel that whatever caused that other problem is still present, unless you inadvertently removed the problem code recently.
aidin Tajadod 2-Nov-10 13:25pm    
You are right, but I could not found the problem and it seems it is a bug! ( I don't say it is .net bug, but there is a bug outside of my code and I could not find that! :( )
Although even using Win API did not solve the problem!! but now it seems that it is working better.

Even though you've opened the file for writing, the file pointer or the current file position will always be in the beginning when a file is opened. You can move the file pointer to the end of the file using SetFilePointer and specifying the last parameter as FILE_END with distance to move as 0.
 
Share this answer
 
Comments
aidin Tajadod 1-Nov-10 20:13pm    
thanks _Superman, Actually you are write but it does not work even for new files. ( I just call createfile once and then use writefile )
Actually I found the answer!!
I have to define my OverLap variable as a local variable and add the code below after each writefile

OverLap.OffsetLow += System.Convert.ToInt32(LenWritten) ;


!!!

Thanks guy.
 
Share this answer
 

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