Solved

Write string to text file C#

Posted on 2009-05-06
16
2,695 Views
Last Modified: 2013-12-17
Hello,

I have a long text string and I need to save it to text file.
I have "Save" button and string. How to do it? How to open a file a nd write to it? I never worked with files.

THANKS
0
Comment
Question by:margarit
  • 6
  • 4
  • 4
  • +1
16 Comments
 
LVL 6

Accepted Solution

by:
Cebik earned 300 total points
ID: 24312934
StreamWriter str = new StreamWriter("c:\test.txt");
str.WriteLine(yourstring);
str.Close();
0
 
LVL 16

Assisted Solution

by:CuteBug
CuteBug earned 200 total points
ID: 24312938
You can call File.WriteAll() method.


using System.IO;
 
string str = "Data to write";
File.WriteAll(@"C:\Temp\MyFile.txt", str);

Open in new window

0
 
LVL 6

Expert Comment

by:Cebik
ID: 24312948
0
3 Use Cases for Connected Systems

Our Dev teams are like yours. They’re continually cranking out code for new features/bugs fixes, testing, deploying, testing some more, responding to production monitoring events and more. It’s complex. So, we thought you’d like to see what’s working for us.

 
LVL 8

Expert Comment

by:Pearl_export_ben
ID: 24312951
Modify this script so that when your user clicks save, the WriteToFile Function is called.  aRandomVariableContainingMoreText (Below) can be replaced by the contents of wherever your users are typing like SW.WriteLine(Text1.text) or similar


    StreamWriter SW;
    SW=File.CreateText("c:\\MyTextFile.txt");
    SW.WriteLine("This is your first line of text");
    SW.WriteLine(aRandomVariableContainingMoreText);
    SW.Close();

Open in new window

0
 
LVL 8

Expert Comment

by:Pearl_export_ben
ID: 24312955
PS, a good source for working with text files in C# is:

http://www.csharphelp.com/archives/archive24.html

I used it when i learned and I would recommend it to anyone :)

Ben
0
 

Author Comment

by:margarit
ID: 24312978
Hello,
Thanks for all the fast answers!!!
If my string contains "\n" - new line. Would it go to a new line in a text file. If not how to do it?
 
THANKS
0
 
LVL 16

Expert Comment

by:CuteBug
ID: 24313019
You need to split the string into an array of strings.

            string testString = "This\nis\njust\na\ntest\nof\nmultiple\nlines.";
            string[] lines = testString.Split(new char[] { '\n' });
            File.WriteAllLines(@"C:\Temp\testFile.txt", lines);

Open in new window

0
 
LVL 6

Expert Comment

by:Cebik
ID: 24313021
i don't think so..
if you want only add something to file then:

and..
WOW how many fast answers :)

StreamWriter sw = new StreamWriter(@"C:\test.txt", true)
sw.Write(yourString);
sw.WriteLine(yourString2);

Open in new window

0
 

Author Comment

by:margarit
ID: 24313195
Hello!
THANKS AGAIN!!!
I use the following method to write to file:
StreamWriter sw = new StreamWriter(@"C:\test2.txt", true);
The problem that if the file test2 already exists it does not rewrite it. It append my text to already existed text in the file.
How can I delete the text in file? Or re-create the file?
THANKS
0
 
LVL 6

Expert Comment

by:Cebik
ID: 24313222
try
StreamWriter sw = new StreamWriter(@"C:\test2.tx
t", false);
0
 
LVL 16

Expert Comment

by:CuteBug
ID: 24313224
You need to use FileStream class for that

FileStream fs = new FileStream(@"C:\test2.txt", FileMode.CreateNew, FileAccess.Write, FileShare.Read);
StreamWriter sw = new StreamWriter(fs);

This will recreate the file.
0
 
LVL 16

Expert Comment

by:CuteBug
ID: 24313237
Oops!
Just a small typo. It should be FileMode.Create instead of FileMode.CreateNew.
FileStream fs = new FileStream(@"C:\test2.txt", FileMode.Create, FileAccess.Write, FileShare.Read);
StreamWriter sw = new StreamWriter(fs); 

Open in new window

0
 

Author Comment

by:margarit
ID: 24313251
Hello!
THANKS AGAIN!!!
I tried StreamWriter sw = new StreamWriter(@"C:\test2.tx
t", false);

and it works fine
THANKS A LOT!!!!
0
 
LVL 6

Expert Comment

by:Cebik
ID: 24313262
but this one create new or/and recreate file (checked)
StreamWriter sw = new StreamWriter(@"C:\test2.txt", false);

but i think CuteBug found beter solution:
and its creating new file and rewriting also

File.WriteAllText(@"c:\s.txt", yourString);

Open in new window

0
 

Author Closing Comment

by:margarit
ID: 31578384
THANKS A LOT!!! YOU HELPED ME A  LOT
0
 
LVL 6

Expert Comment

by:Cebik
ID: 24313282
@margarit

my pleasure! :)
0

Featured Post

DevOps Toolchain Recommendations

Read this Gartner Research Note and discover how your IT organization can automate and optimize DevOps processes using a toolchain architecture.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Today I had a very interesting conundrum that had to get solved quickly. Needless to say, it wasn't resolved quickly because when we needed it we were very rushed, but as soon as the conference call was over and I took a step back I saw the correct …
Entity Framework is a powerful tool to help you interact with the DataBase but still doesn't help much when we have a Stored Procedure that returns more than one resultset. The solution takes some of out-of-the-box thinking; read on!
This Micro Tutorial demonstrates using Microsoft Excel pivot tables, how to reverse engineer competitors' marketing strategies through backlinks.
Email security requires an ever evolving service that stays up to date with counter-evolving threats. The Email Laundry perform Research and Development to ensure their email security service evolves faster than cyber criminals. We apply our Threat…

816 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

12 Experts available now in Live!

Get 1:1 Help Now