I am writing a text into a file. I am getting a column from database and stored it in a string and writing it in a text file. That column contains c# code and it is writing like a single line with small squares for next line(space). I need to write it line by line. Here is my code.
using (var dest = File.AppendText(Path.Combine(_logFolderPath, "a.txt")))
{
dest.WriteLine(line.TrimStart());
}
Any suggestion?
Does Notepad show small squares for new lines, but when you look at the file in Visual Studio it's OK? If so, my guess is that this will fix it:
dest.WriteLine(line.TrimStart().Replace("\n", Environment.NewLine));
try this
File.AppendAllText(Path.Combine(_logFolderPath, "a.txt",
line.Trim() + Environment.NewLine));
dest.WriteLine(line.TrimStart().Replace("\n", Environment.NewLine).Replace("\r", Environment.NewLine));
Related
I have this block of code and want to insert headers before it writes. I have tried various ways but it keeps reading and mixing the headers with the data being written to file. I tried adding the heading outside the if block but it still makes no difference, I also tried adding it right after the file is created but same result. I would like to know how to add it without it mixing with the data
using (StreamWriter stream = new StreamWriter("cross_check.xls", true))
{
if (stream == null)
{
MessageBox.Show("File can't be written");
}
else
{
stream.WriteLine();
stream.Write(search.Text);
stream.Write("\t ");
stream.Write(textBox1.Text);
MessageBox.Show("Data Added Successfully");
}
You can include the header when you write data to file. But if you have some existing files which need modification and if the content of your excel file is text contents (which seems to be, based on the question), you can simply use File.ReadAllLines and File.WriteAllLines this way:
var file = #"d:\file.xls";
var lines = System.IO.File.ReadAllLines(file).ToList();
lines.Insert(0, "Some text");
System.IO.File.WriteAllLines(file, lines);
Using File.ReadAllLines you have all lines of your file and you can perform additional processing on file contents too. For example you can split all lines by a delimiter and manipulate each cell or add new columns and so on. Also you can shape the result into a data structure like DataTable and show it in DataGridView to edit them and save them back to the file again.
I have this string read from a table in sql:
Yderligere tillidshverv:
Medlem af bestyrelsen for Dansk XXSW, region Ã…rhus.
Andre aktiviteter:
Opfinder af 123 trapper.
What I want to do is replace occurences of \r\n with just a single \n. However it is not working. The problem is that notepad++ still shows CRLF. It should only show LF. What am I missing? Here is my code:
string x = returnValue.Replace("\r\n", "\n");
When you paste a string from a Windows clipboard into Notepad++, the linebreaks get converted to the line ending style set for the current document (see the bottom of the screen).
If you right click and select UNIX, you will be able to paste the string with \n only. This will also change all line endings to LF.
If you do not want to change all line endings in the document to LF, you can use EDIT > Paste Special -> Paste Binary Content
However, from C#, you can just write the variable content into a text file:
var s = "I know\r\nit should\r\n";
var b = s.Replace("\r\n", "\n");
using (var sw = new StreamWriter(#"PATH_TO_FILE", false, Encoding.UTF8))
{
sw.Write(b);
}
And enjoy \n linebreaks.
Using the Regex class will work. I used linqpad to quickly test code which has the Dump() extension method
Regex.Replace("test\r\ntest","\r\n","\n").Select(x => x).Dump();
Update : A regular replace also works BTW. You state that it doesn't?
"test\r\ntest".Replace("\r\n","\n").Select(x => x).Dump();
I have this bit of code below which saves perfectly fine to a text file, however there is no formatting that is transferred, for example, The below words would save as THISISATESTLAYOUT. I would like the desired output displayed below:
THIS
IS
A
TEST
LAYOUT
I know there's something obvious im missing here so thanks for any help
if (entity.Switch == true)
{
string path = #"filepath....\\Test.txt";
if (!File.Exists(path))
{
// Create a file to write to.
using (StreamWriter sw = File.CreateText(path))
{
sw.Write(entity.comments);
}
}
}
this string is saved in one entity called comments and displays fine within the C# application.
sw.Write and sw.WriteLine both give the same single line output with no spaces
and also entity.comments references a column in an SQL Server Table, and is a VARCHAR(MAX)
you may be using '\n' for newlines. If so use
sw.Write(entity.comments.Replace("\n", "\r\n"));
Change sw.Write to sw.WriteLine
I think my question is simple. I've searched but not found a solution for the method that I'm actually using.
I save the content of a listbox into a text file with success, but I'm having problem on load.
For create the file, I use:
using(StreamWriter file = File.CreateText(path))
To write the content from the listbox to file, I use:
foreach (string content in listDOF.Items)
{
file.WriteLine(content);
}
This works very well.
Now, I just need load the saved content with succes.
I've tried:
if (File.Exists(filesrc))
{
File.OpenRead(filesrc);
string[] line = System.IO.File.ReadAllLines(filesrc);
listDOF.Items.Add(line);
}
But this does not work and give me an exception.
How to do this correctily? Thanks all in advance! :)
You are adding an array of strings. The method to use is AddRange
string[] lines = System.IO.File.ReadAllLines(filesrc);
listDOF.Items.AddRange(lines);
The File.OpenRead is not needed. You could remove that line
how do i read the second line of text in visual studio 2012 c#
the txt file
user123
**12345**
asdfd
i want to get the second line in one button1_click and show it to textblock2
i did try learn from here
How do I read a specified line in a text file?
and here
How to skip first line and start reading file from second line in C#
but no one of these works because theres difference i couldnt apply in my code
any help?
=================================================================================
sorry to confusing you all
actually im really lacking experience in programming and i hardly know how to use it
right now im using vs2012 in windows8 , is that mean i was coding in winrt?
btw , i appreciate all your help and successfully applying answer to my code
this is the actual code
var file = await ApplicationData.Current.LocalFolder.GetFileAsync(tb1.Text+".txt");
var line = await FileIO.ReadLinesAsync(file);
if (tb2.Text == line[2])
{
tb3.Text = (line[1]);
}
var desiredText = File.ReadLines("C:\myfile.txt").ElementAt(1);
File.ReadLines() returns an String[] of the lines in a file. The index of the second line is 1. See this.
try
var desiredText = File.ReadLines("C:\myfile.txt");
textbox1.text = desiredText[1];
Just call a .ReadLine() before you start capturing the content of the file.
Essentially this will make the reader skip the first line of the file and take only the 2nd line and all lines that follow it.
// Try this to take the second line.
string line;
using (var file_read = new StreamReader(your_file))
{
file_read.ReadLine();
line = file_read.ReadLine();
}
textBox1.Text = line.ToString();