Can write to csv file but not append - c#

string pathDesktop = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
string filePath = pathDesktop + "\\mycsvfile.csv";
string delimter = ",";
string a = "Enoelpro---[037,033,0,018,030,012,004,021,009,038,035,053,044,050,074,F,018,010,070,000]<Vulpix>[-][037,034,0,022,020,029,002,008,024,036,046,049,041,057,077,F,018,005,070,000]<Vulpix>[-] cual es mejor??";
List<string[]> test = conv(a,"testrainer");
int length = test.Count;
using (TextWriter writer = File.CreateText(filePath))
{
for (int index = 0; index < length; index++)
{
writer.WriteLine(string.Join(delimter, test[index]));
}
}
So, at the momement, this works fine, except it doesn't keep the old data in the csv file. How can I modify this so instead of deleting the data, it simply appends to the data?

Can you please try with StreamWriter class?
If the file exists, it can be either overwritten or appended to. If the file does not exist, this constructor creates a new file.
Instead using
TextWriter writer = File.CreateText(filePath) try to use
TextWriter writer = new StreamWriter(filePath, true);
If you pass true in constructor it should append text to file.

File.CreateText Method (String)
This method is equivalent to the StreamWriter(String, Boolean)
constructor overload with the append parameter set to false. If the
file specified by path does not exist, it is created. If the file does
exist, its contents are overwritten. Additional threads are permitted
to read the file while it is open.
StreamWriter Constructor (String, Boolean)
Here second parameter, true to append data to the file; false to overwrite the file.
If you check the documentation for each method it cleary say the answers for your questions and also there is a suggetion in case of you need to append the file. Use StreamWriter constructor with path and append parameter (true)

Related

c# File.WriteAllText overwriting new text on old Text

While inserting new text into Json file its overwriting new text (insted of writing in new line).
Here is my code
public static void WriteToJson()
{
string filepath = #"../../SchemaList.json";
// string filepath = #"C:\HoX_code\learning\Readjson\Readjson\SchemaList.json";
List<SchemaInfo> _oscheme = new List<SchemaInfo>();
_oscheme.Add(new SchemaInfo()
{
AuthenticateCmdlets= "AuthenticateCmdlets1",
GetPowerState= "GetPowerState1",
PowerOff= "PowerOff",
PowerOn= "PowerOn",
});
string json = JsonConvert.SerializeObject(_oscheme.ToArray(), Formatting.Indented);
using (StreamWriter sw = new StreamWriter(#"C:\HoX_code\learning\Readjson\Readjson\SchemaList.json"))
{
sw.Write(json);
}
/// File.WriteAllText(#"../../SchemaList.json", json);
}
Here i use File.WriteAllText & StreamWriter Both are working same
This is intended behaivour. Checking the documentation for File.WriteAllText it says
Creates a new file, write the contents to the file, and then closes the file. If the target file already exists, it is overwritten.
(Emphasis mine)
You're going to want to use File.AppendAllText, it's documentation states
Appends the specified string to the file, creating the file if it does not already exist.
If you want to use streams, then the StreamWriter constructor has a parameter to specify whether or not to append or overwrite text in a file here (Credits go to #vernou, I totally forgot this constructor existed)
But do note that this will result in invalid JSON, as JSON may only have 1 base object and this will result in multiple. If you actually want to append to the serialized JSON object, the I recommend you check out How to Append a json file without disturbing the formatting

StreamWriter adds extra character(s) on new line(s) at the end of file

I'm trying to modify an .ini file, in C# with .NET 5.0, using FileStream and StreamReader / StreamWriter. I just need to modify the first line of the file so I read the entire file into a list of strings called strList, modify the first line, and then write it all back to the same file.
List<string> strList = new List<string>();
using (FileStream fs = File.OpenRead(#"C:\MyFolder\test.ini"))
{
using (StreamReader sr = new StreamReader(fs))
{
while (!sr.EndOfStream)
{
strList.Add(sr.ReadLine());
}
}
}
strList[0] = "test01";
using (FileStream fs = File.OpenWrite(#"C:\MyFolder\test.ini"))
{
using (StreamWriter sw = new StreamWriter(fs))
{
for (int x = 0; x < ewsLines.Count; x++)
{
sw.WriteLine(strList[x]);
}
}
}
The issue I'm running into is that I'll have new character(s) at the end of my file on new line(s). I verified that the number of lines I read from the file matches what is in the file and that the for loop only writes that same number of lines back into the file. I don't have any issues writing other strings except for "test01". This string is the only one that causes the issue that I just described. It seems to be grabbing characters from the last line like R or LAYER from MULTI_LAYER.
Ex 1: This
S10087_U1
Cq4InEq=TRUE
XtrVer=5.5
IOCUPDATEMDB=TRUE
ARCHITECTURE=MULTI_LAYER
Becomes this
test01
Cq4InEq=TRUE
XtrVer=5.5
IOCUPDATEMDB=TRUE
ARCHITECTURE=MULTI_LAYER
R
Ex 2: This
test01 - Copy
Cq4InEq=TRUE
XtrVer=5.5
IOCUPDATEMDB=TRUE
ARCHITECTURE=MULTI_LAYER
ER
Becomes this
test01
Cq4InEq=TRUE
XtrVer=5.5
IOCUPDATEMDB=TRUE
ARCHITECTURE=MULTI_LAYER
LAYER
Replacing the StreamWriter portion with the following seems to fix the issue but I'm trying to figure out why using StreamWriter doesn't work as I expect it to.
File.WriteAllLines(#"C:\MyFolder\test.ini", strList);
This is because you're using File.OpenWrite. From the remarks in the documentation:
The OpenWrite method opens a file if one already exists for the file path, or creates a new file if one does not exist. For an existing file, it does not append the new text to the existing text. Instead, it overwrites the existing characters with the new characters. If you overwrite a longer string (such as "This is a test of the OpenWrite method") with a shorter string (such as "Second run"), the file will contain a mix of the strings ("Second runtest of the OpenWrite method").
While you could just change your code to use File.Create instead, I'd suggest changing the code more significantly - not just the writing, but the reading too:
string path = #"C:\MyFolder\test.ini";
var lines = File.ReadAllLines(path);
lines[0] = "test01";
File.WriteAllLines(path, lines);
That's much simpler code to do the same thing.
The half-way house between the two would be to use File.OpenText (to return a StreamWriter) and File.CreateText (to return a StreamWriter). There's no need to do the wrapping yourself.

Method that writes list of strings to file works only the last time when it`s called

I wrote function for writing list of strings to file
and I need to call it multiple times however it works only the last time when I call it
public static void WriteToFile(string UserText, List<string> ListToBeWritten, string Path)
{
using (StreamWriter sw = new StreamWriter(Path))
{
sw.WriteLine(UserText);
foreach (var lines in ListToBeWritten)
{
sw.WriteLine(lines);
}
}
}
The way you create a new StreamWriter it will overwrite the contents of the file if it exists every time. If you just want to append to an existing file you could set the append parameter to true when instantiating the writer using this constructor:
using (StreamWriter sw = new StreamWriter(Path, append: true))
Quote from the documentation:
Initializes a new instance of the StreamWriter class for the specified
file by using the default encoding and buffer size. If the file
exists, it can be either overwritten or appended to. If the file does
not exist, this constructor creates a new file.

using StreamWriter in .NET

I have a console application which writes details of the processed jobs into .txt file. I use this code to do it:
StreamWriter jp = new StreamWriter(jobsProcessed);
jp.WriteLine(DateTime.Now.ToString());
jp.WriteLine(info);
jp.WriteLine("------");
jp.Close();
Unfortunately every time a job is being processed new "info" string replaces the previous one. Is there any method to add new text to the end or beginning of the text file?
You can use StreamWriter Constructor (String, Boolean), where second boolean parameter indicates either the data has to be appended to the already available one or not.
And also avoid calling Close and use using statement
using(StreamWriter jp = new StreamWriter(jobsProcessed))
{
jp.WriteLine(DateTime.Now.ToString());
jp.WriteLine(info);
jp.WriteLine("------");
//jp.Close(); //NO NEED MORE
}
The good about this that even if exception occures, which can happen, the stream will be Disposed, by the way.
There is an overload to the StreamWriter constructor which takes a second parameter called append;
using (StreamWriter jp = new StreamWriter(jobsProcessed, true))
{
jp.WriteLine(DateTime.Now.ToString());
jp.WriteLine(info);
jp.WriteLine("------");
}
It's also better practice to wrap your StreamWriter up in a using block like above.
StreamWriter jp = new StreamWriter(jobsProcessed,true);
Second parameter
//Determines whether data is to be appended to the file. If the file exists
//and append is false, the file is overwritten. If the file exists and append
// is true, the data is appended to the file. Otherwise, a new file is created.
http://www.dotnetperls.com/streamwriter
http://social.msdn.microsoft.com/Forums/zh/clr/thread/17cd8ccf-7e53-41de-b4cc-221da70405a4
Just amend this:
StreamWriter jp = new StreamWriter(jobsProcessed);
To this:
StreamWriter jp = new StreamWriter(jobsProcessed, true);
// using (StreamWriter jp = new StreamWriter(jobsProcessed)) Overwrites, not good for you!
using (StreamWriter jp = new StreamWriter(jobsProcessed, true)) // Appends, good for you!
{
jp.WriteLine(DateTime.Now.ToString());
jp.WriteLine(info);
jp.WriteLine("------");
}
But you could semplify your code like so:
String[] content = File.ReadAllLines(jobsProcessed);
String[] newContent = new String[3];
newContent[0] = DateTime.Now.ToString();
newContent[1] = info;
newContent[2] = "------";
File.AppendAllLines(jobsProcessed, newContent);

How to write at the next line in the next opening of the csv file?

At first run, my program, writes to a csv file in the first line,
But, when I'm running my program at the second.. third.. time, it runs over the first line..
how can i correct it?
I would like to have a CSV file input of all the entering to my program.
The code is as follows:
private void WriteToCsvFile()
{
var us = users.ElementAt(0);
string names = "Number',";
string userAnswer = (us.userName + ",");
foreach (string ss in user)
{
string str = Path.GetFileName(ss);
names = names + str + ",";
}
foreach (string ans in us.answer)
{
userAnswer = userAnswer + ans + ",";
}
using (StreamWriter sw = new StreamWriter("EntranceLog.csv"))
{
sw.WriteLine(names);
sw.WriteLine(userAnswer);
}
this.Close();
}
Add true parameter in the constructor:
using (StreamWriter sw = new StreamWriter("EntranceLog.csv", true))
The second parameter named append controls whether an existing file shall be overwritten or appended. MSDN states:
true to append data to the file; false to overwrite the file. If the specified file does not exist, this parameter has no effect, and the constructor creates a new file.
Each time it is run, you are creating a new file with the same name is overwriting the older file. That is the default behavior of the specific constructor you are using.
You want to use this constructor instead and specify the append parameters as true:
using (StreamWriter sw = new StreamWriter("EntranceLog.csv", true))
{
// write your file as normal
}

Categories