Click here to Skip to main content
15,884,099 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I want to write a string to text file in windows mobile..Can some one please help me..I tried lots of ways but There is an IO Exception fires.
Thanks..
Posted
Comments
Marcin Kozub 17-Mar-14 7:39am    
Can you post some of your code? What exception do you get?
manojmadhuranga 17-Mar-14 8:00am    
File.Create("..\\..\\code.txt").Close();

StreamWriter swFile = new StreamWriter(new FileStream("date.txt",FileMode.Truncate),Encoding.ASCII);

swFile.Write("new text");

swFile.Close();

1 solution

First of all I don't understand what is File.Create for?
Second, You're creating FileStream with mode FileMode.Truncate. This mode according to MSDN:
"Specifies that the operating system should open an existing file. When the file is opened, it should be truncated so that its size is zero bytes. This requires FileIOPermissionAccess.Write permission. Attempts to read from a file opened with FileMode.Truncate cause an ArgumentException exception."

I'm assuming you're getting FileNotFoundException, because file "date.txt" does not exist, which is required by FileMode.Truncate.

Instead of using FileStream, you can do this in easier way:

C#
using (var swFile = new StreamWriter("date.txt", false, Encoding.ASCII))
{
    swFile.Write("new text");
}


In this case StreamWriter has 3 parameters:
1. Path to file
2. Append (bool)
2.1 If is set to True, and file exists it will append data to end of file
2.2 If is set to False, and file exists it will open file, truncate it's contents and set its position to 0
2.3 If file not exists in both cases it will create new file and set its position to 0.
3. Encoding.

By using using clause you don't have to close stream, beacuse StreamWriter implements IDisposable interface and at the end of using block it will be closed automatically.

Here you have some useful informations:
1. http://msdn.microsoft.com/library/system.io.filemode%28v=vs.110%29.aspx[^]
2. http://msdn.microsoft.com/pl-pl/library/system.io.streamwriter%28v=vs.110%29.aspx[^]

Hope it helps you a little bit.
 
Share this answer
 
v2
Comments
manojmadhuranga 18-Mar-14 6:57am    
Thanks for your Solution...
I have asked another Question on Windows mobile..
Can you help me to solve that.

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