Exporting datagridview to csv file

LINQ FTW! var sb = new StringBuilder(); var headers = dataGridView1.Columns.Cast<DataGridViewColumn>(); sb.AppendLine(string.Join(“,”, headers.Select(column => “\”” + column.HeaderText + “\””).ToArray())); foreach (DataGridViewRow row in dataGridView1.Rows) { var cells = row.Cells.Cast<DataGridViewCell>(); sb.AppendLine(string.Join(“,”, cells.Select(cell => “\”” + cell.Value + “\””).ToArray())); } And indeed, c.Value.ToString() will throw on null value, while c.Value will correctly convert to an empty string.

Add a new line at a specific position in a text file.

This will add the line where you want it. (Make sure you have using System.IO; and using System.Linq; added) public void CreateEntry(string npcName) //npcName = “item1” { var fileName = “test.txt”; var endTag = String.Format(“[/{0}]”, npcName); var lineToAdd = “//Add a line here in between the specific boundaries”; var txtLines = File.ReadAllLines(fileName).ToList(); //Fill a list … Read more

Writing file to web server – ASP.NET

protected void TestSubmit_ServerClick(object sender, EventArgs e) { using (StreamWriter _testData = new StreamWriter(Server.MapPath(“~/data.txt”), true)) { _testData.WriteLine(TextBox1.Text); // Write the file. } } Server.MapPath takes a virtual path and returns an absolute one. “~” is used to resolve to the application root.

simultaneous read-write a file in C#

Ok, two edits later… This should work. The first time I tried it I think I had forgotten to set FileMode.Append on the oStream. string test = “foo.txt”; var oStream = new FileStream(test, FileMode.Append, FileAccess.Write, FileShare.Read); var iStream = new FileStream(test, FileMode.Open, FileAccess.Read, FileShare.ReadWrite); var sw = new System.IO.StreamWriter(oStream); var sr = new System.IO.StreamReader(iStream); var … Read more

Should I call Close() or Dispose() for stream objects?

A quick jump into Reflector.NET shows that the Close() method on StreamWriter is: public override void Close() { this.Dispose(true); GC.SuppressFinalize(this); } And StreamReader is: public override void Close() { this.Dispose(true); } The Dispose(bool disposing) override in StreamReader is: protected override void Dispose(bool disposing) { try { if ((this.Closable && disposing) && (this.stream != null)) { … Read more

Append lines to a file using a StreamWriter

Use this instead: new StreamWriter(“c:\\file.txt”, true); With this overload of the StreamWriter constructor you choose if you append the file, or overwrite it. C# 4 and above offers the following syntax, which some find more readable: new StreamWriter(“c:\\file.txt”, append: true);