Solved

Write string to text file C#

Posted on 2009-05-06
16
2,712 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 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
How Do You Stack Up Against Your Peers?

With today’s modern enterprise so dependent on digital infrastructures, the impact of major incidents has increased dramatically. Grab the report now to gain insight into how your organization ranks against your peers and learn best-in-class strategies to resolve incidents.

 
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

Forrester Webinar: xMatters Delivers 261% ROI

Guest speaker Dean Davison, Forrester Principal Consultant, explains how a Fortune 500 communication company using xMatters found these results: Achieved a 261% ROI, Experienced $753,280 in net present value benefits over 3 years and Reduced MTTR by 91% for tier 1 incidents.

Question has a verified solution.

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

This document covers how to connect to SQL Server and browse its contents.  It is meant for those new to Visual Studio and/or working with Microsoft SQL Server.  It is not a guide to building SQL Server database connections in your code.  This is mo…
Many of us here at EE write code. Many of us write exceptional code; just as many of us write exception-prone code. As we all should know, exceptions are a mechanism for handling errors which are typically out of our control. From database errors, t…
Nobody understands Phishing better than an anti-spam company. That’s why we are providing Phishing Awareness Training to our customers. According to a report by Verizon, only 3% of targeted users report malicious emails to management. With compan…
Attackers love to prey on accounts that have privileges. Reducing privileged accounts and protecting privileged accounts therefore is paramount. Users, groups, and service accounts need to be protected to help protect the entire Active Directory …

763 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