473,545 Members | 2,113 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Save a string to a text file


I would like to open a text file titled (c:\logs.txt).
If the file doesn't exist i would like to create it.
if it does exist i would like to append to it.

I would like to insert a line into the end of the file.
The line is contained in the variable 'line' which is a string
variable.

once i've done this i would like to close the file.

Nov 7 '06 #1
7 41990
thankyou

Nov 7 '06 #2
I would like to open a text file titled (c:\logs.txt). If the file
doesn't exist i would like to create it. if it does exist i would like
to append to it.

I would like to insert a line into the end of the file.
The line is contained in the variable 'line' which is a string
variable.
once i've done this i would like to close the file.
Look at the System.IO.File class in the MSDN documentation. It has everything
that you want.

private void WriteLinesToFil e(string filePath, string[] lines)
{
if (filePath == null || filePath.Length == 0)
return;
if (lines == null || lines.Length == 0)
return;

StreamWriter fileWriter = null;
try
{
if (File.Exists(fi lePath))
fileWriter = File.AppendText (filePath);
else
fileWriter = File.CreateText (filePath);

foreach (string line in lines)
fileWriter.Writ e(line);
}
finally
{
if (fileWriter != null)
fileWriter.Clos e();
}
}

Best Regards,
Dustin Campbell
Developer Express Inc.
Nov 7 '06 #3


"Dustin Campbell" <du*****@no-spam-pleasedevexpres s.comwrote in message
news:c1******** *************** ***@news.micros oft.com...
>I would like to open a text file titled (c:\logs.txt). If the file
doesn't exist i would like to create it. if it does exist i would like
to append to it.

I would like to insert a line into the end of the file.
The line is contained in the variable 'line' which is a string
variable.
once i've done this i would like to close the file.

Look at the System.IO.File class in the MSDN documentation. It has
everything that you want.

private void WriteLinesToFil e(string filePath, string[] lines)
{
if (filePath == null || filePath.Length == 0)
return;
if (lines == null || lines.Length == 0)
return;

StreamWriter fileWriter = null;
try
{
if (File.Exists(fi lePath))
fileWriter = File.AppendText (filePath);
else
fileWriter = File.CreateText (filePath);

foreach (string line in lines)
fileWriter.Writ e(line);
}
finally
{
if (fileWriter != null)
fileWriter.Clos e();
}
}

Best Regards,
Dustin Campbell
Developer Express Inc.

To modify the posted code:

StreamWriter fileWriter = null;
if (File.Exists(fi lePath))
fileWriter = File.AppendText (filePath);
else
fileWriter = File.CreateText (filePath);
try {
foreach (string line in lines)
fileWriter.Writ e(line);
} finally {
fileWriter.Clos e();
}
Notice, no extra checking in the finally block. If we get that far, the
file was opened. Since the file is opened right before the try...catch
block, the fileWriter will contain a reference unless an exception was
closed, in which case, no writer will be opened (and the reference will
still be null).

HTH,
Mythran
Nov 7 '06 #4
To modify the posted code:
>
StreamWriter fileWriter = null;
if (File.Exists(fi lePath))
fileWriter = File.AppendText (filePath);
else
fileWriter = File.CreateText (filePath);
try {
foreach (string line in lines)
fileWriter.Writ e(line);
} finally {
fileWriter.Clos e();
}
Notice, no extra checking in the finally block. If we get that far,
the file was opened. Since the file is opened right before the
try...catch block, the fileWriter will contain a reference unless an
exception was closed, in which case, no writer will be opened (and the
reference will still be null).
Of course, at this point it isn't necessary to set "fileWriter " to null at
all.

StreamWriter fileWriter;
if (File.Exists(fi lePath)
fileWriter = File.AppendText (filePath);
else
fileWriter = File.CreateText (filePath);

try {
foreach (string line in lines)
fileWriter.Writ e(line);
}
finally {
fileWriter.Clos e();
}

Best Regards,
Dustin Campbell
Developer Express Inc.
Nov 7 '06 #5
Dustin Campbell <du*****@no-spam-pleasedevexpres s.comwrote:
Of course, at this point it isn't necessary to set "fileWriter " to null at
all.

StreamWriter fileWriter;
if (File.Exists(fi lePath)
fileWriter = File.AppendText (filePath);
else
fileWriter = File.CreateText (filePath);

try {
foreach (string line in lines)
fileWriter.Writ e(line);
}
finally {
fileWriter.Clos e();
}
Given that AppendText creates the file if it doesn't exist (according
to the documentation) you can use:

using (StreamWriter writer = File.AppendText (filePath))
{
foreach (string line in lines)
{
writer.Write (line);
}
}

--
Jon Skeet - <sk***@pobox.co m>
http://www.pobox.com/~skeet Blog: http://www.msmvps.com/jon.skeet
If replying to the group, please do not mail me too
Nov 7 '06 #6
Given that AppendText creates the file if it doesn't exist (according
to the documentation) you can use:

using (StreamWriter writer = File.AppendText (filePath))
{
foreach (string line in lines)
{
writer.Write (line);
}
}
Perfect. Thanks Jon.

Best Regards,
Dustin Campbell
Developer Express Inc.
Nov 7 '06 #7


"Dustin Campbell" <du*****@no-spam-pleasedevexpres s.comwrote in message
news:c1******** *************** ***@news.micros oft.com...
>Given that AppendText creates the file if it doesn't exist (according
to the documentation) you can use:

using (StreamWriter writer = File.AppendText (filePath))
{
foreach (string line in lines)
{
writer.Write (line);
}
}

Perfect. Thanks Jon.

Best Regards,
Dustin Campbell
Developer Express Inc.

Aye, now if we all combine all our thought processes for our life works, all
would be good...

:-)

Mythran

Nov 7 '06 #8

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

6
3533
by: BadOmen | last post by:
I have a text file that I want to save from my program. But I don't want to save the empty lines. I want to delete everything after the last character, Is that possible? Then when I read the text file i don't want to read empty lines(If the user as edit the file in notpad..), sense it makes commas at all new lines and then split the text at...
4
25007
by: Andras Gilicz | last post by:
Hi VB fans I'm working on a relatively large project in VB6 with about a dozen forms, including graphs, labels, text boxes, etc. The software itself is actually a flow simulator with more or less complex technical calculations, several input variables. I would like to equipp the starting panel with the usual New, Open, Save, Save As, Close...
2
13079
by: gnv | last post by:
Hi all, I am writing a cross-browser(i.e. 6 and netscape 7.1) javascript program to save an XML file to local file system. I have an xml string like below: var xmlStr = "<?xml version="1.0" encoding="UTF-8"?><a>some info</a>"; I want to save this xml file to local file system with JavaScript,
4
4511
by: Jae | last post by:
I'm writing a web application that exports and imports excel files. The application gets a list of users and their info and displays it in a datagrid .The user then selects to save the file as a tab delimited file or an excel file. The application then saves the file in the correct format. The flip side is for the user to import/upload the...
4
3704
by: Glenn M | last post by:
I have a shared XML file on a server . i also have one xslt file that performs a simple transform on in to view the data. now i want to have another page that lets users modify the shared xml file via some editable controls such as text boxes , option boxes etc. how can i implment this , should i use another xslt file with <INPUT>...
8
2669
by: DanB | last post by:
This is probably soooo simple but I can't seem to get it. I have a text file that I want users to download via a web page. I want the file to be saved to a default folder (or one that they choose) on the users / client file system. I have toyed with a Self-Extracting zip file but the contents of my zip file changes each time it is...
4
3607
by: Jeff | last post by:
Hi, I'd like to be able to prompt the user to save text that a script has created to a file. The idea is that the script would create a text string, the "Save As" dialog would be triggered and then the user could choose to save the text that was created somewhere on their local filesystem. This has none of the security concerns of...
2
10973
by: vbaDev | last post by:
Hi. I am using Access 2000 and in my code I'm exporting a table into an Excel file (creating it), then the code needs to export another query into the same file (a new worksheet). So I needed both a "Save As" dialog and the ability to grab the filepath so that the second export appends to it. Anyway, I found Microsofts method and it works,...
2
3019
by: chike_oji | last post by:
Please can someone help me. I am writing a web application, that allows for the upload of an excel sheet into the database. I have an upload button and a save button. The upload button allows for the retrieval of the excel data into a DataTable, which is bound to a GridView for previewing before saving to the Database. But, whenever I...
0
7401
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language...
1
7423
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For...
0
7757
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the...
0
5972
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then...
0
4945
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert...
0
3450
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in...
1
1884
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
1
1014
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
0
704
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.