c# - Reading lines from text file and adding to listbox - c#

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

Related

Prepend headers to my c# excel output file

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.

Save a multi-line string to a text file on multiple lines

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

ListView formatting when reading from text file

I'm trying to read data from a text file and populate that data in a listview. However, when I read the data in and then add it to the listview, it is trying to put everything on the same line just in different columns. I would like it to read each line of the txt file and put each line in its own row in the listview. Can anyone help me out with this? Not much experience using listviews, or reading from text files for that matter.
Thanks for any help.
string path = #"..\..\blah.txt";
StreamReader textIn = new StreamReader(new FileStream(path, FileMode.Open, FileAccess.Read));
while (textIn.Peek() != -1)
{
string str = textIn.ReadLine();
listviewOptions.Items.Add(str);
}
textIn.Close();
You can use the code below to read and populate your listview in one go:
listviewOptions.Items.AddRange(File.ReadLines(#"..\..\blah.txt").ToArray());
It uses File.ReadLines method to read lines from your file and List.Items.AddRange to add them all.

read the second line from the text

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();

Problem loading RTF file into windows richTextBox

I am trying to load files into a windows froms (vs 2010) richTextBox but only the first line of the file is loading. I'm using:
// Create an OpenFileDialog to request a file to open.
OpenFileDialog openFile1 = new OpenFileDialog();
// Initialize the OpenFileDialog to look for RTF files.
openFile1.DefaultExt = "*.rtf";
openFile1.Filter = "RTF Files|*.rtf";
// Determine whether the user selected a file from the OpenFileDialog.
if (openFile1.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
// Load the contents of the file into the RichTextBox.
rtbTest.LoadFile(openFile1.FileName, RichTextBoxStreamType.PlainText);
}
I've tried using rtf files created in word or word pad and have tried saving .cs files as .rtf without any success.
Any help appreciated please.
Okay,
It looks like the whole rtb.LoadFile() thing isn't working for yah. Could you please try loading the file this way?:
using(var of = new OpenFileDialog())
{
of.DefaultExt="*.rtf";
of.Filter = "RTF Files|*.rtf";
if(of.ShowDialog() == DialogResult.OK)
rtb.Rtf = System.IO.File.ReadAllText(of.FileName);
}
I hope this helps.
I don't think the cs file is truly rtf. Try using the overload of LoadFile with a stream type such as
rtbTest.LoadFile(openFile1.FileName, RichTextBoxStreamType.PlainText);
Other than that, are you sure the rich text box is big enough to show more than the first line?
Edit
I tried it. I used windows forms in vs2010 (I think you are using windows forms, but not 100% sure). I created an windows forms project and saved the Project.cs as rtf. I added a button and a RichTextBox in the button's click handler I added the code from the question. It actually threw an exception when I loaded Program.rtf because it was not in the right format. I added the RichTextBoxStreamType.PlainText argument to the LoadFile call and it worked. It showed the whole file.
How did you originally save the RTF file in the first place? I agree with Mike Two, the file has got stuff in it that is not really RTF.
You might verify that the file loads properly using Wordpad, which is what I use when working with RTF files.
Update:
One investigative technique you might try is th following: after loading the file into the RichTextBox, check what the debugger gives for the RichTextBox.Rtf property - you should see all the RTF text including formatting. If it is indeed "all there" then you know you're reading the file correctly.
What worries me is that you're trying to view a code file, saved as RTF. This obviously should not be a problem, however, I recommend saving a very simple RTF file with maybe two lines of just normal text (think: lorem ipsum). If that loads ok, then you'll know it's something specific within your code file that you're reading that is screwing things up. Highly unlikely, but it's an obvious troubleshooting tactic.
As a last resort, try it on a different machine.
When all else fails, check the silly stuff... have you set the RichTextBox control be multiline? Or is it set to single line mode? Perhaps you are correctly loading the entire file, but the control is only displaying the first line because that's what you told it :)
Check RichTextBox.Multiline. It's a longshot, but maybe?
I created a sample project with a docked RichTextBox control, kept all the defaults (except Dock = DockStyle.Fill), added a simple File->Open menu and cut'n'pasted your code into the menu handler. The only change I had to make to your code was to change the second LoadFile parameter from RichTextBoxStreamType.PlainText to RichTextBoxStreamType.RichText.
A complex file (links, formatting, graphics, etc) saved from Word opened just fine for me.
Another common problem is that the control is very short. You might think it is filling your client area, but in actuality it is just a narrow strip, so you only see a single line tall. Have you set the size, docking and/or anchor properties properly? Do you see a scrollbar for your document? Is it shorter than you expect?
This will work:
StreamReader sr = new StreamReader(sFileName, Encoding.Default, true);
string sRtfFile = sr.ReadToEnd();
sr.Close();
rtbCombinedFile.Rtf = sRtfFile;
sFileName is of course the full path of the RTF file. StreamReader is part of "System.IO."
Just read a textfile into a string and set the Rtf property of the RichTextBox.
If you're not sure if your text contains Rtf text you could use this class that I wrote. It inherits from the original RichTextBox and has a fallback if the content isn't rtf or wrong formatted.
public class RichTextBoxEx :RichTextBox
{
public new String Rtf
{
get
{
return base.Rtf;
}
set
{
try
{
// is this rtf?
if (Regex.IsMatch(value, #"^{\\rtf1"))
{
base.Rtf = value;
}
else
{
base.Text = value;
}
}
catch (ArgumentException) // happens if rtf content is corrupt
{
base.Text = value;
}
}
}
}
I think the problem is with the RichTextBoxStreamType because you set it to PlainText but you want the RichText to be loaded in the richtextbox control so why not use RichTextBoxStreamType.RichText I have tried the following code and it works properly.
// Create an OpenFileDialog to request a file to open.
OpenFileDialog openFile1 = new OpenFileDialog();
// Initialize the OpenFileDialog to look for RTF files.
openFile1.DefaultExt = "*.rtf";
openFile1.Filter = "RTF Files|*.rtf";
// Determine whether the user selected a file from the OpenFileDialog.
if (openFile1.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
// Load the contents of the file into the RichTextBox.
richTextBox1.LoadFile(openFile1.FileName, RichTextBoxStreamType.RichText);
}
Not sure if it is the same in WinForms as it is in WPF, but in WPF you have to use a FlowDocument set to the Document Property of the RichTextBox.
this is the code I have to read from a WebStream (same thing can be done for FileStreams
protected static FlowDocument LoadRemoteRtf(string path)
{
var doc = new FlowDocument();
if (!string.IsNullOrEmpty(path))
{
var range = new TextRange(doc.ContentStart, doc.ContentEnd);
var downloader = new WebClient();
Stream stream = null;
try
{
stream = downloader.OpenRead(path);
range.Load(stream, DataFormats.Rtf);
}
catch (Exception ex)
{
var props = new Dictionary<string, object> {{"URL", path}};
Logging.WriteLogEntry("Failed to load remote RTF document.", ex, TraceEventType.Information, props);
}
finally
{
if (stream != null)
{
stream.Close();
}
downloader.Dispose();
}
}
return doc;
}
MyRTB.Document = LoadRemoteRtf("http://myserver.com/docs/remote.rtf");
You can also try setting your RichTextBox Modifiers property to "public" and see if that works, also check that WordWrap property is set to true, that is if the file you are reading is all written on 1 line, just a long line, even if not it will still wrap those long lines based on the size of your RichTextBox.
I don't know if you use it already, have you tried ReSharper?

Categories

Resources