this is my first post, and I am new to C# so please be gentle :P.
I am writing application that is reading some txt files and then displaying them in gridview (I am later doing some more things with it, but it is not important right now). Almost all of my files have some established system of characters (there are always three columns that are separated with coma) and here I have no problem with reading them putting in list and then bind into gridview.
But I also have some files that don't have same system of characters, and I have problem with dealing with them. Can You help me to somehow format them to this original system of characters (I mean this one with commas). Bellow is my function for loading everything into list and then into gridview. I also posted example of file with good system of characters, and this one which is not formated.
29-01-2013 03:49:31.629,Some text ghs(23).asv1, more text
17-07-2011 12:12:32.643,Some text also dsad(1), more text
31-01-2013 08:14:08.473,Some text sdfsdfsd[2], more text
Not formated text has some spaces at the beggining, then some number, (dot), and another space. After this I would like to start reading and get rid of everything that was before. Moreover between my proper data it does not have commas but spaces. It is sth like this.
Please guys can You help me??
23-05-2009 12:12:45.675 Some text fsdf1 some more text
13-02-2003 11:12:45.454 Some text sdfsdfS(1) some more text
private void button7_Click(object sender, EventArgs e)
{
List<MyColumns> list = new List<MyColumns>();
OpenFileDialog openFile1 = new OpenFileDialog();
openFile1.Multiselect = true;
if (openFile1.ShowDialog() != DialogResult.Cancel)
{
foreach (string filename in openFile1.FileNames)
{
using (StreamReader sr = new StreamReader(filename))
{
string line;
while ((line = sr.ReadLine()) != null)
{
string[] _columns = line.Split(",".ToCharArray());
MyColumns mc = new MyColumns();
mc.Time = _columns[0];
mc.System_Description = _columns[1];
mc.User_Description = _columns[2];
list.Add(mc);
}
}
}
DataTable ListAsDataTable = BuildDataTable<MyColumns>(list);
DataView ListAsDataView = ListAsDataTable.DefaultView;
this.dataGridView1.DataSource = view = ListAsDataView;
this.dataGridView1.AllowUserToAddRows = false;
dataGridView1.ClearSelection();
}
textBox1.Text = this.dataGridView1.Rows.Count.ToString();
}
I was thinking also about using reg expresions, format of my text would look like this. Field1>(6)Field2>(23)Field3>(2)Field4>(50+) field 3 are spaces that work as delimiters, is it possible to change them to commas, while working with text??
If it is fixed-width columns, then one way would be using string.Substring and then trimming the results for each column with string.Trim.
Is it a CSV File - are all Fields delimeted with ",". If so do yourself a favor and do not attempt to parse the csv on your own - doing it right can be quite tricky.
I had greadt sucess with KBCSV a free C# library which can read csv files into datatables easily.
Related
I'm building a website in ASP.net and, in this case, I'm simply trying to read a .txt file and output it into a textbox whenever that page loads. I wrote this code so I could execute my idea:
protected void Page_Load(object sender, EventArgs e)
{
foreach (string line in System.IO.File.ReadLines(#"file_path"))
{
TextBox1.Text = line;
}
}
However, this is not working, as when I execute the website on this page, nothing loads. There is no exception that is being called or any error.
What can I do?
If you need more details or information, please don't refrain from asking.
Edit: I think it's important to say that I've tested doing
TextBox1.Text = "Hello World";
And that worked properly.
Well, to read the text, this works:
string sFile = #"C:\TEST2\T.txt";
string sTextData = File.ReadAllText(sFile);
TextBox1.Text = sTextData;
And if some some reason, you LEFT OUT some HUGE MASSIVE WHOPPER detail, say like you only want the first line of text from the file?
Then this:
string sFile = #"C:\TEST2\T.txt";
string sTextData = File.ReadAllText(sFile);
string strFirstLine = sTextData.Split(System.Environment.NewLine.ToCharArray())[0];
TextBox1.Text = strFirstLine;
FYI:
Don't forget to set the text box to multiline if you need/want to have more then one line of text display in that box.
As pointed out, we can use this:
File.ReadAllLines(sFile).FirstOrDefault();
however, the above still reads the whole text file.
If the text file is to be large, and we still want the first line, or wish to read + process line by line, then this is better:
StreamReader sR = new StreamReader(sFile);
int i = 0;
while (!sR.EndOfStream)
{
i++;
Debug.Print(i.ToString() + "->" + sR.ReadLine());
if (i >= 1)
break;
}
sR.Close();
So, above would read line by line, and if the text file was large, or we wish to only pull + read the first line from the file? Then of course the above example is better, since only the first line (or several lines if i condition is changed) is better from a performance + io point of view.
To read the first line, you can simply write this File.ReadLines(“YourFileName”).FirstOrDefault;
You need to use the method File.ReadAllText. It reruns the string value. And you can then assign to Text property.
File.ReadLines returns Ienumerable<string> not string .
I have been trying for a while now to export a data table to csv in visual studio after datalogging.
For some reason I get weird results when importing into excel whereas notepad is fine. It seems line breaks are being added in but at random points within the data.
I have battling this for a while now so any help is appreciated!
Excel Version
Notepad Version
void SaveAllData()
{
{
saveFileDialog1.InitialDirectory = "C"; // open save file window
saveFileDialog1.Title = "Save as CSV File"; // promt save as csv
saveFileDialog1.FileName = DateTime.Now.ToString("dd.MM.yy_HH.mm");
saveFileDialog1.Filter = "CSV File | *.csv"; // csv format
if (saveFileDialog1.ShowDialog() != DialogResult.Cancel) // if save dialog opens
{
string value = "";
DataGridViewRow dr = new DataGridViewRow();
StreamWriter swOut = new StreamWriter(saveFileDialog1.FileName, true, Encoding.ASCII);
//write header rows to csv
for (int i = 0; i <= IncomingDataTable.Columns.Count - 1; i++)
{
if (i > 0)
{
swOut.Write(",");
}
swOut.Write(IncomingDataTable.Columns[i].HeaderText);
}
swOut.WriteLine();
//write DataGridView rows to csv
for (int j = 0; j <= IncomingDataTable.Rows.Count - 1; j++)
{
if (j > 0)
{
swOut.WriteLine();
}
dr = IncomingDataTable.Rows[j];
for (int i = 0; i <= IncomingDataTable.Columns.Count - 1; i++)
{
if (i > 0)
{
swOut.Write(",");
}
value = dr.Cells[i].Value.ToString();
swOut.Write(value);
}
}
swOut.Close();
}
MessageBox.Show("Your data has been successfully saved.", "Message", MessageBoxButtons.OK, MessageBoxIcon.Information); // alert user file has saved
serialPort1.Close(); // close serial port
Setup_Page f1 = new Setup_Page(); // open setup page
this.Hide();
f1.ShowDialog();
Close(); // close this page
}
}
If your input data contains linefeeds and you output them, some applications will treat them as line breaks but some won’t. Notepad does not, so it looks like a single line to Notepad. Excel recognizes the linefeeds and begins a new row. Open the CSV file in WordPad instead of Notepad; WordPad will recognize linefeeds whereas they are invisible in Notepad.
The simple fix is to call String.Trim on your input data before writing it. However, as Magnus mentioned, libraries are your friend. If you had used a good one, this may not have been a problem in the first place, as a well-written library would have handled embedded newlines in the data.
You may say that you can trim newlines. Well, what if a newline is in the middle of your data? Trim won’t handle that. There won’t be any newlines? What about commas? There won’t be any commas, because the data is only numeric? What if it is a decimal, and the computer that produced it is in France, or numerous other countries that use the comma as the decimal separator? What about quotes in the data? A library may have already handled all these cases. (The comma decimal separator may still be a problem to whoever uses the output, but at least the CSV will be well-formed.)
Note, though, that CSV is not a well-defined standard. Different applications and libraries use different strategies to handle the above cases, so if your library didn’t use the same format as Excel, it still might not load correctly.
I want to write a message in Hebrew to a text file. I tried the following:
using (StreamWriter sw = File.CreateText(path + FileName))
{
sw.WriteLine(sms);
}
However, the message comes out left to right. How can I write right to left?
A string is an Array of Chars so you can
Char[] tempArray = sms.ToCharArray()
Array.Reverse(tempArray)
sms = new String(tempArray)
This should reverse the array therefore when you write it will read right to left.
well, it doesn't really matter how you write them in.
Here's a little example:
void Main()
{
string lines = "First line.\r\nSecond line.\r\nThird line.";
var = new System.IO.StreamWriter("c:\\test_eng.txt");
file.WriteLine(lines);
file.Close();
string hebrew = #"מספרים רצים מימין לשמאל ?";
file = new System.IO.StreamWriter("c:\\test_heb.txt");
file.WriteLine(hebrew);
file.Close();
}
Upon opening the files, you'll find that hebrew is hebrew, and display from right to left.
Are you experiencing any funny behavior?
You can also try defining your string culture to hebrew:
// Creates and initializes the CultureInfo which uses the international sort.
CultureInfo myCIintl = new CultureInfo( "he", false );
More on that here (MSDN).
Some more thinking -> I doubt the above will change much for the display, it'll be more useful for dates for example. But atm, I'm not able to see hebrew on my console output ... What are you outputting to? Just txt, HTML, or something else?
I am attempting to build a tool using C# to modify the config files for our software. The config files are in the following format:
SERVER_NAME TestServer
SERVER_IP 127.0.0.1
SERVICE_NUMBER 4
SERVICE_ID 1 2 3 4
And so on. Each line is prefaced with an identifier(Ex: SERVER_NAME), then the value. I need the tool to load the value for each identifier into a separate text box. When the user clicks save, it needs to write the updated information to the file.
I am entirely lost on how I should load the data into the text boxes, so if you could provide some help on that, I would appreciate it.
Writing it, I am assuming the easiest way, since all of the data will be loaded, is to erase the previous data, and write the new data to the file. This I should be able to handle without a problem. If there is a better way to do this, I am definitely willing to try.
I would greatly appreciate some pointers on how to get started with loading the data.
private void openToolStripMenuItem_Click(object sender, EventArgs e)
{
openFD.ShowDialog();
openFD.Title = "Open a Config File...";
openFD.InitialDirectory = "C:";
openFD.FileName = "";
openFD.Filter = "CONFIG|*.cfg";
string selected_file = "";
selected_file = openFD.FileName;
using (StreamReader sr = new StreamReader(selected_file))
{
string currLine;
while ((currLine = sr.ReadLine()) != null)
{
}
}
}
To read each line of the file you could do something like this:
// StreamReader is in System.IO
using(StreamReader sr = new StreamReader("config file path here"))
{
string currLine;
while((currLine = sr.ReadLine()) != null)
{
// currLine will have the current line value as a string
// You can then manipulate it any way you like
// Or store it in an array or List<>
}
}
If you need help with adding items into a textbox, just ask.
Hope this helps!
I am new to programming and am working on a C# project that will search and replace certain words in a text file with new values. I have some code that works, but the OLD and NEW values are hardcoded right now. I would like to use an external CSV file as a configuration file so the user can add or update the OLD to NEW mappings at a later time. This is my current code with the OLD and NEW values hardcoded:
try
{
StreamReader file = new StreamReader(inputfullfilepath);
TextWriter writer = new StreamWriter(outputfile);
while ((line = file.ReadLine()) != null)
{
line = line.Replace("OLD1", "NEW1");
line = line.Replace("OLD2", "NEW2");
// etc....
writer.WriteLine(line);
}
file.Close();
File.Move(inputfullfilepath, inputfullfilepath + ".old");
writer.Close();
File.Move(outputfile, outputfilepath + #"\" + inputfilename);
MessageBox.Show("File Scrub Complete", "Success");
}
catch
{
MessageBox.Show("Error: Be sure data paths are valid.", "Error",
MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
}
The code takes each line of the text file, tries to do a search/replace for all OLD to NEW mappings, then goes to the next line in the text file. The problem I am trying to wrap my head around is being able to make this list of OLD to NEW mappings dynamic based on a CSV (or XML if that would be easier?) configuration file so the user can add new search/replace keywords.
I tried to use the C# Application Settings in Visual Studio (which creates an XML configuration file) but I had a really hard time understanding how to make that work. What's the best way to do this so the values don't have to be hardcoded?
A csv file will work just fine.
I'll create a new Object which i'll call ReplaceObject
public ReplaceObject()
{
public string original;
public string updated;
//ideally you'd use getters and setters, but I'll keep it simple
}
Now we read from the csv
List<ReplaceObject> replaceList = new List<ReplaceObject>
while (reader.peek != -1)
{
string line = reader.readln();
var splitLine = line.split(',');
ReplaceObject rObject = new ReplaceObject();
rObject.original = splitLine[0];
rObject.updated = splitLine[1];
replaceList.add(rObject);
}
Now we go through the list.. and replace
string entireFile = //read all of it
foreach (ReplaceObject o in replaceList)
{
entireFile.Replace(o.original,o.updated);
}
//write it at the end
(Note that my code is missing some checks, but you should get the idea. Also you might want to use a StringBuilder)
My suggestion would be that you use the Settings.cs instead of CSV
It is very easy to use them and involves very less code
e.g. Properties.Settings.Default.Old1;
Here is a walkthrough http://msdn.microsoft.com/en-us/library/aa730869(v=vs.80).aspx
See this example showing how you can use it http://www.codeproject.com/Articles/17659/How-To-Use-the-Settings-Class-in-C