I'm writing a list to a file, the list gets data from the form app from text I type in. This works but it overwrites the file every time I start the form instead of saving it and adding new data. How Can I add "AppendAllLines" or "WriteAllLines" to this as a solution?
public List<String> listDeliveries()
{
List<String> listDeliveries = new List<string>();
using (StreamWriter writer = new StreamWriter("Database.txt"))
{
foreach (Delivery del in deliveries)
{
String delAsString = del.summary();
listDeliveries.Add(delAsString);
writer.WriteLine(delAsString);
}
}
return listDeliveries;
}
var listDeliveries = deliveries.Select(d=>d.summary()).ToList();
File.AppendAllLines("Database.txt", listDeliveries);
return listDeliveries;
You can use ToList to create your list and File.AppendAllLines to append the lines from the list:
List<string> listDeliveries = deliveries.Select(d => d.summary())
.ToList();
File.AppendAllLines("Database.txt", listDeliveries);
How Can I add "AppendAllLines" or "WriteAllLines" to this as a solution?
Well it looks like you just want:
List<String> listDeliveries = deliveries.Select(x => x.summary()).ToList();
File.AppendAllLines("Database.txt", listDeliveries);
return listDeliveries;
(Yes, you can create the StreamWriter with true as the second argument, but AppendAllLines is simpler...)
You can use
using (StreamWriter writer = new StreamWriter("Database.txt", true))
To append rather than overwrite
Use overloaded constructor that allows you to specify whether to append or not. The default is false
StreamWriter writer = new StreamWriter("Database.txt", true)
When you create the StreamWriter, pass in a boolean that will tell it to append data to the file instead of overwrite.
using (StreamWriter writer = new StreamWriter("Database.txt", true))
Related
I went through documentation and I didn't see anything for it. I'm using the same exact write function from documentation but the problem is I also need to append. So far I've tried reading it than adding the CSV into a list than I write the list to CSV. Is there a better way I could append?
The exact write function I use with my own variables
var records = new List<Foo>
{
new Foo { Id = 1, Name = "one" },
};
using (var writer = new StreamWriter("path\\to\\file.csv"))
using (var csv = new CsvWriter(writer, CultureInfo.InvariantCulture))
{
csv.WriteRecords(records);
}
What I use to read but with my own variables:
using (var reader = new StreamReader("path\\to\\file.csv"))
using (var csv = new CsvReader(reader, CultureInfo.InvariantCulture))
{
var records = csv.GetRecords<Foo>();
}
Hopefully someone can help!
Use the StreamWriter(String, Boolean) constructor to specify you want to append to an existing file:
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.
Parameters
path
String
The complete file path to write to.
append
Boolean
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.
As for your CsvHelper CsvWriter, you need to configure it to omit the header depending on if you are appending or creating:
bool append = true;
var config = new CsvConfiguration(CultureInfo.InvariantCulture);
config.HasHeaderRecord = !append;
using (var writer = new StreamWriter("path\\to\\file.csv", append))
{
using (var csv = new CsvWriter(writer, config))
{
csv.WriteRecords(records);
}
}
I have a text file "cars.txt" that is saved in a bin\debug and I would like to add more care models to it using C# and display the whole content of the file with new added lines. How do I do that?
string[] models = new string[] { "Toyota", "Nissan" };
using (StreamWriter writer = new StreamWriter("CarsList.txt"))
{
foreach (string s in models)
{
writer.WriteLine(s);
listBoxCars.Items.Add(s);
}
}
There are several ways to do this, the easiest of which might be to just pass true as a second parameter to your StreamWriter constructor, which instructs it to append text:
string[] models = { "Toyota", "Nissan" };
using (StreamWriter writer = new StreamWriter("CarsList.txt", true))
{
foreach (string s in models)
{
writer.WriteLine(s);
}
}
You can then easily get the entire file contents into a string using File.ReadAllText:
string fileContents = File.ReadAllText("CarsList.txt");
Or if you want to read in each line as a separate item, you can use File.ReadAllLines (note that this is not inside the using block above - this should be after that part has completed and the new items are added to the file):
foreach (var item in File.ReadAllLines(fileName))
{
listBox1.Items.Add(item);
}
I tried to write to CSV file using CsvHelper in C#.
This is the link to the library http://joshclose.github.io/CsvHelper/
I used the code in web site.
Here is my code:
var csv = new CsvWriter(writer);
csv.Configuration.Encoding = Encoding.UTF8;
foreach (var value in valuess)
{
csv.WriteRecord(value);
}
It writes only a part of data to csv file.
Last rows were missing.
Could you please help with this.
You need to flush the stream. The Using statement will flush when out of scope.
using (TextWriter writer = new StreamWriter(#"C:\test.csv", false, System.Text.Encoding.UTF8))
{
var csv = new CsvWriter(writer);
csv.WriteRecords(values); // where values implements IEnumerable
}
when, I added this code after the loop code is working well
var csv = new CsvWriter(writer);
csv.Configuration.Encoding = Encoding.UTF8;
foreach (var value in valuess)
{
csv.WriteRecord(value);
}
writer.Close();
The problem occurred because I did not close the Connection
Assuming that writer is some kind of TextWriter, you should add a call to flush the contents before closing the writer:
writer.Flush()
If the last lines are missing, this is the most likely reason.
Adding to #greg's answer:
using (var sr = new StreamWriter(#"C:\out.csv", false, Encoding.UTF8)) {
using (var csv = new CsvWriter(sr)) {
csv.WriteRecords(values);
}
}
Using the following code:
string lines = "";
using (StreamReader sr = new StreamReader(#"file.txt"))
{
lines = sr.ReadLine();
}
using (StreamWriter writer = new StreamWriter(#"file.txt"))
{
writer.Write(lines); // Change this to skip the first line
}
How can I make it rewrite everything EXCEPT the first line?
Maybe you can try this:
var lines = File.ReadLines("file.txt").Skip(1).ToList();
File.WriteAllLines("file.txt",lines);
It will write all the lines to your file except the first line and replace your file content.So basically it will remove the first line from your file.
var allLinesExceptFirstOne = System.IO.File.ReadAllLines(filename).Skip(1).ToList();
I am trying to serialize my Report class info to an XML. At this point I think all of the serialize and deserialize code works, but for the initial write, I'm having trouble performing the serialize, because the XML file doesn't exist yet.
for an empty text file, i can use:
StreamWriter sw = File.CreateText(#"path");
sw.Close();
this is my code block for the serializing. the exception (Directory not found) is getting thrown on the StreamWriter line. I'd like to simply add an if(!File.Exists(xmlPath))...create empty XML. Or maybe there is a more correct way to do this.
public void SerializeToXML(Report newReport)
{
XmlSerializer serializer = new XmlSerializer(typeof(Report));
TextWriter textWriter = new StreamWriter(xmlPath);
serializer.Serialize(textWriter, newReport);
textWriter.Close();
}
The StreamWriter(String) constructor will create the file if it does not already exist:
If the file exists, it is overwritten; otherwise, a new file is created.
However, it will not create any inexistent directories in your path.
DirectoryNotFoundException: The specified path is invalid, such as being on an unmapped drive.
To create any required directories, you can include the following code (at the beginning of your SerializeToXML method):
var dir = Path.GetDirectoryName(xmlPath);
if (!Directory.Exists(dir))
Directory.CreateDirectory(dir);
First to make sure the directory exist you can use:
Directory.CreateDirectory(#"c:\directory\subdirectory");
You don't have to check if directory already exist.
A easy way to convert public classes to XML is to use the following snippet:
public static string ToXml<T>(T obj)
{
using (var ms = new MemoryStream())
using (var sr = new StreamReader(ms))
{
var xmlSer = new XmlSerializer(typeof(T));
xmlSer.Serialize(ms, obj);
ms.Seek(0, SeekOrigin.Begin);
return sr.ReadToEnd();
}
}
Then you could just use the following code to write it to a file:
var xmlString = Util.ToXml(report);
File.WriteAllText(#"path", xmlString);
(this example is without error handling)
Also, in your code you forgot to close/dispose the TextWriter. I would recommend using the using-statement to handle it for you.
CreateText, and the StreamWriter, will create files if they don't exist, but they won't create directories that don't already exist for you. Is your path correct?
Try Checking with a Directory.Exists(Path.GetDirectoryName(xmlPath)).