Open existing file, append a single line - c#

I want to open a text file, append a single line to it, then close it.

You can use File.AppendAllText for that:
File.AppendAllText(#"c:\path\file.txt", "text content" + Environment.NewLine);

using (StreamWriter w = File.AppendText("myFile.txt"))
{
w.WriteLine("hello");
}

Choice one! But the first is very simple. The last maybe util for file manipulation:
//Method 1 (I like this)
File.AppendAllLines(
"FileAppendAllLines.txt",
new string[] { "line1", "line2", "line3" });
//Method 2
File.AppendAllText(
"FileAppendAllText.txt",
"line1" + Environment.NewLine +
"line2" + Environment.NewLine +
"line3" + Environment.NewLine);
//Method 3
using (StreamWriter stream = File.AppendText("FileAppendText.txt"))
{
stream.WriteLine("line1");
stream.WriteLine("line2");
stream.WriteLine("line3");
}
//Method 4
using (StreamWriter stream = new StreamWriter("StreamWriter.txt", true))
{
stream.WriteLine("line1");
stream.WriteLine("line2");
stream.WriteLine("line3");
}
//Method 5
using (StreamWriter stream = new FileInfo("FileInfo.txt").AppendText())
{
stream.WriteLine("line1");
stream.WriteLine("line2");
stream.WriteLine("line3");
}

Or you could use File.AppendAllLines(string, IEnumerable<string>)
File.AppendAllLines(#"C:\Path\file.txt", new[] { "my text content" });

Might want to check out the TextWriter class.
//Open File
TextWriter tw = new StreamWriter("file.txt");
//Write to file
tw.WriteLine("test info");
//Close File
tw.Close();

The technically best way is probably this here:
private static async Task AppendLineToFileAsync([NotNull] string path, string line)
{
if (string.IsNullOrWhiteSpace(path))
throw new ArgumentOutOfRangeException(nameof(path), path, "Was null or whitepsace.");
if (!File.Exists(path))
throw new FileNotFoundException("File not found.", nameof(path));
using (var file = File.Open(path, FileMode.Append, FileAccess.Write))
using (var writer = new StreamWriter(file))
{
await writer.WriteLineAsync(line);
await writer.FlushAsync();
}
}

File.AppendText will do it:
using (StreamWriter w = File.AppendText("textFile.txt"))
{
w.WriteLine ("-------HURRAY----------");
w.Flush();
}

//display sample reg form in notepad.txt
using (StreamWriter stream = new FileInfo("D:\\tt.txt").AppendText())//ur file location//.AppendText())
{
stream.WriteLine("Name :" + textBox1.Text);//display textbox data in notepad
stream.WriteLine("DOB : " + dateTimePicker1.Text);//display datepicker data in notepad
stream.WriteLine("DEP:" + comboBox1.SelectedItem.ToString());
stream.WriteLine("EXM :" + listBox1.SelectedItem.ToString());
}

We can use
public StreamWriter(string path, bool append);
while opening the file
string path="C:\\MyFolder\\Notes.txt"
StreamWriter writer = new StreamWriter(path, true);
First parameter is a string to hold a full file path
Second parameter is Append Mode, that in this case is made true
Writing to the file can be done with:
writer.Write(string)
or
writer.WriteLine(string)
Sample Code
private void WriteAndAppend()
{
string Path = Application.StartupPath + "\\notes.txt";
FileInfo fi = new FileInfo(Path);
StreamWriter SW;
StreamReader SR;
if (fi.Exists)
{
SR = new StreamReader(Path);
string Line = "";
while (!SR.EndOfStream) // Till the last line
{
Line = SR.ReadLine();
}
SR.Close();
int x = 0;
if (Line.Trim().Length <= 0)
{
x = 0;
}
else
{
x = Convert.ToInt32(Line.Substring(0, Line.IndexOf('.')));
}
x++;
SW = new StreamWriter(Path, true);
SW.WriteLine("-----"+string.Format("{0:dd-MMM-yyyy hh:mm:ss tt}", DateTime.Now));
SW.WriteLine(x.ToString() + "." + textBox1.Text);
}
else
{
SW = new StreamWriter(Path);
SW.WriteLine("-----" + string.Format("{0:dd-MMM-yyyy hh:mm:ss tt}", DateTime.Now));
SW.WriteLine("1." + textBox1.Text);
}
SW.Flush();
SW.Close();
}

Related

Convert CSV in XML file with C#

I wrote this piece of code that allows me to read a CSV file and convert it to an XML file.
I have a problem, if inside the CSV file there are semicolons (;) the program cannot read the data instead, if there are commas (,) that delimit the words the program can read the data and to insert them correctly in the XML file.
could you find a way to replace the semicolon (;) with the comma (,)?
Thank you very much!! :)
This is the code:
writer.WriteStartDocument();
writer.WriteStartElement("DC8_Recipes");
using (CsvReader reader = new CsvReader(path))
{
reader.ReadHeaders();
while (reader.ReadRecord())
{
writer.WriteStartElement("DC8_Recipes");
writer.WriteAttributeString("PlantNo", reader["id_imp"]);
writer.WriteAttributeString("No", reader["nome_frm"]);
writer.WriteAttributeString("Name", reader["desc_frm"]);
writer.WriteEndElement();
}
reader.Close();
}
writer.WriteEndElement();
writer.WriteEndDocument();
writer.Close();
logText.Text += DateTime.Now + " Convertion Completed\n";
logText.Text += DateTime.Now + " Saving file to: " + savepath + "\n";
try
{
logText.Text += DateTime.Now + " File save completed!\n";
logText.Text += DateTime.Now + " process END\n";
}
catch
{
}
}
You can pass into CsvReader constructor a CsvConfiguration to change the default delimiter (which is based on the current CultureInfo):
The culture is used to determine the default delimiter, default line ending, and formatting when type converting.
using (var csv = new CsvReader(writer, new CsvConfiguration(CultureInfo.InvariantCulture)
{
Delimiter = ","
}))
{
csv.Read();
}
You could write your own CsvReader:
public static List<Model> ReadCsv(string path)
{
var modelList = new List<Model>();
using (var fileStream = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read))
{
using (var streamReader = new StreamReader(fileStream, Encoding.Default))
{
while (!streamReader.EndOfStream)
{
var line = streamReader.ReadLine();
if (string.IsNullOrEmpty(line))
{
continue;
}
var splittedLine = line.Split(';');
var model = new Model();
for (var i = 0; i < splittedLine.Length; i++)
{
switch (i)
{
case 0:
model.FirstColumn = splittedLine[i];
break;
case 1:
model.SecondColumn = splittedLine[i];
break;
case 2:
model.ThirdColumn = Convert.ToInt32(splittedLine[i]);
break;
}
}
modelList.Add(model);
}
}
}
return modelList;
}

IOException caused by file being in use

I have a problem that I know people already asked here but I tried the solution they bring but it's not helping.
My problem: I'm doing a program in C# with 2 forms. My main form is used to read a file .txt and put the information in a DataGridView:
public void LireFichier()
{
DataGridView dataGridView1 = new DataGridView();
string delimeter = ";";
string tableName = "Clients";
string filePath = #"C:...\Clients.txt";
DataSet dataset = new DataSet();
using (StreamReader sr = new StreamReader(filePath))
{
dataset.Tables.Add(tableName);
dataset.Tables[tableName].Columns.Add("ID");
dataset.Tables[tableName].Columns.Add("Name");
dataset.Tables[tableName].Columns.Add("LastName");
dataset.Tables[tableName].Columns.Add("Datet");
dataset.Tables[tableName].Columns.Add("Price");
dataset.Tables[tableName].Columns.Add("Phone");
dataset.Tables[tableName].Columns.Add("ID box");
string allData = sr.ReadToEnd();
string[] rows = allData.Split("\r".ToCharArray());
foreach (string r in rows)
{
string[] items = r.Split(delimeter.ToCharArray());
dataset.Tables[tableName].Rows.Add(items);
}
this.dataGridView1.DataSource = dataset.Tables[0].DefaultView;
}
My second form is used to add a client in my .txt file :
private void btn_Confirmer_Click(object sender, EventArgs e)
{
string filePath = #"...\Clients.txt";
Client client = new Client();
client.Id = idClient++;
client.Name = tb_name.Text;
client.LastName = tb_lastName.Text;
client.Date = dtp_date.Value.ToString("dd-MMM-yyyy");
client.Price = Convert.ToInt32(tb_price.Text);
client.Phone = tb_telephone.Text;
client.ID_Box = Convert.ToInt32(tb_idbox.Text);
string clientInfo = client.Id.ToString() + ";" + client.Name.ToString() + ";" + client.LastName.ToString() + ";" + client.Date.ToString() + ";" +
client.Montant.ToString() + ";" + client.Phone.ToString() + ";" + client.ID_Boc.ToString() + ";";
using (StreamReader sr = new StreamReader(filePath))
{
string allData = sr.ReadToEnd() + clientInfo;
File.WriteAllText(filePath, allData);
}
this.Close();
}
The problem remains in the StreamReader or the File.WriteAllText no matter what I do I always encounter the same exception(System.IO.IOException) that my file is in use when I arrived to write(add a client) in the file in my second form.
The solution that I tried are:
put the using blocks
sr.Close()
sr.Dispose() even if I know that the using block call dispose at the end.
sr.Close() and sr.Dispose() at the end of the instruction.
Try changing to the following since I think the write is interfering with the read you are already performing.
string allData;
using (StreamReader sr = new StreamReader(filePath))
{
allData = sr.ReadToEnd() + clientInfo;
}
this.Close();
File.WriteAllText(filePath, allData);
Trelly indicated the most possible cause of you problem (file already in use). However, the solution containing exception handling should look like this:
try
{
string allData = null;
using (var sr = new StreamReader(filePath))
{
allData = sr.ReadToEnd() + clientInfo;
}
File.WriteAllText(filePath, allData);
}
catch (IOException exc)
{
// exception handling code
}
this.Close();
OR
It looks like you want to just append some text at the end of the file. File.AppendText is your friend:
using (StreamWriter sw = File.AppendText(filePath))
{
sw.Write(clientInfo);
}
To make your blocks of code thread safe, I would use a lock statement.
First declare object, you will perform lock on:
public static readonly Object Locker = new Object();
Then surround your parts of code, where you are working with file with lock statement:
lock(Locker)
{
//perform file operations
}
Remember that both forms have to refer to the same Locker object
After ReadToEnd, close the StreamReader before WriteAllText:
using (StreamReader sr = new StreamReader(filePath))
{
string allData = sr.ReadToEnd() + clientInfo;
sr.Close() ; // <---- add this instruction
File.WriteAllText(filePath, allData);
}

c# Write DataTable Rows in txt File

I have for like 40 rows on My DataTable Displayed in a DataGridView
i'm confused why my method Saves Only One Row in the TextFile :
private void SaveBtn_Click(object sender, EventArgs e)
{
String outputFile;
List<String> ListData = new List<String>();
using (SaveFileDialog sfd = new SaveFileDialog())
{
sfd.Filter = "Txt File|*.Txt";
if (sfd.ShowDialog() != DialogResult.OK)
return;
outputFile = sfd.FileName;
}
DataTable tb = pw.SavedInfo(User_info.UserID);
for (int i = 0; i < tb.Rows.Count; i++)
{
ListData.Add("Name==> " + tb.Rows[i][1].ToString() + " LastName ==> " + tb.Rows[i][2].ToString() + " Email ==> " + tb.Rows[i][3].ToString() );
}
foreach (String s in ListData)
{
using (TextWriter Tw = new StreamWriter(outputFile))
{
Tw.WriteLine(s);
}
}
}
Did i missed something ? cause it was a really long day to keep being focused
Use the same StreamWriter:
using (TextWriter Tw = new StreamWriter(outputFile))
{
foreach (String s in ListData)
{
Tw.WriteLine(s);
}
}
or use the constructor that takes a bool for "append":
foreach (String s in ListData)
{
using (TextWriter Tw = new StreamWriter(outputFile, true))
{
Tw.WriteLine(s);
}
}
File.WriteAllLines(outputFile, lisData);
Use this to write in the file. File.WriteAllLines Documentation

Disposing File Object Properly

Ok so heres the thing. When ever a trigger is hit i append my logs in a specific folder. The code works fine and it appends it correctly but if i try to manually delete the folder from the desktop its giving a "The action cannot be completed cause the folder/file is open in another program";
i guess im not disposing it right but i dont know where i missed it. I know its the folder that is attached to the process cause i tried to delete the .log file inside and it allowed me.
private void LogEvent(string filename,bool AppendTxt,string msg)
{
string sLogFormat = DateTime.Now.ToShortDateString().ToString() + " " + DateTime.Now.ToLongTimeString().ToString() + " ==> ";
msg = sLogFormat + msg;
// create directory
if (System.IO.Directory.Exists("C:\\Users\\DT-Npax\\Desktop\\LOGS1") != true)
{
Directory.CreateDirectory("C:\\Users\\DT-Npax\\Desktop\\LOGS1");
}
string dailyLog = "C:\\Users\\DT-Npax\\Desktop\\LOGS1" + "\\" + filename + ".log";
FileStream FS = null;
//write or append txt
if (!AppendTxt)
{
if (File.Exists(dailyLog))
{
File.Delete(dailyLog);
}
using (FS = File.Create(dailyLog)) { }
FS.Close();
StreamWriter TXT_WRITE = new StreamWriter(dailyLog);
TXT_WRITE.WriteLine(msg);
TXT_WRITE.Close();
}
else
{
if (!File.Exists(dailyLog))
{
using (FS = File.Create(dailyLog)) { }
FS.Close();
}
FileStream FSAppend = new FileStream(dailyLog, FileMode.Append, FileAccess.Write);
StreamWriter TXT_WRITE = new StreamWriter(FSAppend);
TXT_WRITE.WriteLine(msg);
TXT_WRITE.Close();
FSAppend.Close();
}
}
Your code does seem to close the file properly but not in an exception-safe manner.
You also have some unnecessary code in there (like using (FS = File.Create(dailyLog)) { } FS.Close(); ).
The smallest modification looks like this:
else
{
//if (!File.Exists(dailyLog))
//{
// using (FS = File.Create(dailyLog)) { }
// FS.Close();
//}
using (FileStream FSAppend = new FileStream(dailyLog, FileMode.Append, FileAccess.Write))
using (StreamWriter TXT_WRITE = new StreamWriter(FSAppend))
{
TXT_WRITE.WriteLine(msg);
}
//TXT_WRITE.Close();
//FSAppend.Close();
}
But I would rewrite this whole method like:
private void LogEvent(string filename,bool AppendTxt,string msg)
{
string sLogFormat = DateTime.Now.ToShortDateString().ToString() + " "
+ DateTime.Now.ToLongTimeString().ToString() + " ==> ";
msg = sLogFormat + msg;
// create directory
if (System.IO.Directory.Exists("C:\\Users\\DT-Npax\\Desktop\\LOGS1") != true)
{
Directory.CreateDirectory("C:\\Users\\DT-Npax\\Desktop\\LOGS1");
}
string dailyLog = "C:\\Users\\DT-Npax\\Desktop\\LOGS1" + "\\" + filename + ".log";
if (AppendText)
System.IO.File.AppendAllText(dailylog, msg);
else
System.IO.File.WriteAllText(dailylog, msg);
}
There is no need to pre-create or delete files.
Wrap the streams in a using block since they implement IDisposable.
I must say this code is a little odd...
using (FS = File.Create(dailyLog)) { }
FS.Close();
StreamWriter TXT_WRITE = new StreamWriter(dailyLog);
TXT_WRITE.WriteLine(msg);
TXT_WRITE.Close();
Shouldn't it be something like:
using (FileStream FS = File.Create(dailyLog))
{
using(StreamWriter TXT_WRITE = new StreamWriter(dailyLog))
{
TXT_WRITE.WriteLine(msg);
}
}

Output in txt in C# Class library

How can i make output in txt? but not in the event log
public class ProjectHandler:Microsoft.Office.Project.Server.Events.ProjectEventReceiver {
}
public static void WriteToEventLog(string textLog, EventLogEntryType logtype) {
EventLog eventlog = new EventLog();
eventlog.Source = "Project Event Handler";
eventlog.WriteEntry(logtype.ToString() + ":" + textLog, logtype);
}
public override void OnDeleting(PSContextInfo contextInfo, ProjectPreEventArgs e) {
WriteToEventLog(string.Format("Пользователь \"{0}\" удалил проект \"{1}\"", contextInfo.UserName, e.ProjectName), EventLogEntryType.Information);
base.OnDeleting(contextInfo, e);
}
instead of writing to Event log you should write to text file
Add this method
public static void WriteToTextFile(string textLog)
{
FileStream objFS = null;
string strFilePath = AppDomain.CurrentDomain.BaseDirectory + #"\Exception Log\" + System.DateTime.Now.ToString("yyyy-MM-dd ") + "Exception.log";
if (!File.Exists(strFilePath))
{
objFS = new FileStream(strFilePath, FileMode.Create);
}
else
objFS = new FileStream(strFilePath, FileMode.Append);
using (StreamWriter Sr = new StreamWriter(objFS))
{
Sr.WriteLine(System.DateTime.Now.ToShortTimeString() + "---" + textLog);
}
}
then change this line
WriteToEventLog(string.Format("Пользователь \"{0}\" удалил проект \"{1}\"", contextInfo.UserName, e.ProjectName), EventLogEntryType.Information);
to
WriteToTextFile(string.Format("Пользователь \"{0}\" удалил проект \"{1}\"", contextInfo.UserName, e.ProjectName));
Use File.WriteAllText method.
string path = #"c:\temp\MyTest.txt";
string createText = "Hello and Welcome" + Environment.NewLine;
File.WriteAllText(path, createText, Encoding.UTF8);
public override void OnDeleting(PSContextInfo contextInfo, ProjectPreEventArgs e)
{
using (System.IO.StreamWriter sw = new System.IO.StreamWriter(#"C:\Blah.txt"))
{
string textToWrite = string.Format("Пользователь \"{0}\" удалил проект \"{1}\"", contextInfo.UserName, e.ProjectName);
sw.WriteLine(textToWrite);
}
}
Something like this. Use StreamWriter object.
EDIT
Obviously make sure you have access to write to the C:\ drive etc or wherever you want to write too.

Categories

Resources