Load Config file into Windows Forms - c#

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!

Related

File is already use in some other process

Here I want to delete line in a textfiles containg specific string like "21309#003" where item1 is a filename but It shows runtime exception that item1 (file) is already use in some process.How I Solve this problem.I am new in .net C#.
private void button1_Click(object sender, EventArgs e)
{
var selectedItems = listBox1.SelectedItems.Cast<String>().ToList();
foreach (var item in selectedItems)
{
listBox1.Items.Remove(item);
}
foreach (var item1 in selectedItems)
{
listBox1.Items.Remove(item1);
string line = null;
//string line_to_delete = "the line i want to delete";
using (StreamReader reader = new StreamReader(item1))
//item1= "C:\\IMP2711\\textpresent.txt"
{
using (StreamWriter writer = new StreamWriter(item1))
{
while ((line = reader.ReadLine()) != null)
{
//if (String.Compare(line, #"*21349#003*") == 0)
//if (!line.Contains("21349#003") )
if (!line.StartsWith("21349#003"))
{**strong text**
writer.WriteLine(line);
}
}
}
You are reading and writing to the same file at the same time.
var item2 = item1;
If the file is not to big you can read the lines into memory and then write the lines you want to keep back to the file. We can even simplify your code a little bit.
File.WriteAllLines(item1,
File.ReadLines(item1).Where(l => !l.StartsWith("21349#003")).ToList());
Another option if the file is very large is to write to a temporary file. Delete the original and then rename the temporary.
var tmp = Path.GetTempFileName();
File.WriteAllLines(tmp, File.ReadLines(item1).Where(l => !l.StartsWith("21349#003")));
File.Delete(item1);
File.Move(tmp, item1);
If your file is small first read it to memory and then try to write on it, you have two stream on the same file, a file can share between multiple streams but you can not modify a file when it is open by another stream, if your file is huge and you can not moved to memory you can create a temp file and write to temp file when your reading finished replacing original file with temp file and removing temp file.
There's some process that's locking the file c:\imp2711\textpresent.txt. You have to find and kill it.
To find it out, please refer to this question: https://superuser.com/questions/117902/find-out-which-process-is-locking-a-file-or-folder-in-windows

C# text file browse and file write

I have this very large text file (around 35 000+ lines of information) and I would like to extract certain lines from it and place them in another text file.
The text file goes like this:
Feature info
Feature name: 123456
Version: 1
Tokens total: 35
Tokens remaining: 10
And I'd like to extract Feature name and tokens total. What I had in mind was a form with two buttons: 1 for browsing the file and the other to do the whole reading and writing to file part, of course in the same line by line format.
Anyone have any clues on how to do it? I have searched and I haven't really found specific things, also quite new to file read/write...
EDIT
Ok here is what I have so far and it works:
private void button1_Click(object sender, EventArgs e)
{
int counter = 0;
string line;
string s1 = "Feature name";
string s2 = "Tokens total";
// Read the file and display it line by line.
System.IO.StreamReader file = new System.IO.StreamReader("d:\\license.txt");
using (System.IO.StreamWriter file2 = new System.IO.StreamWriter(#"D:\test.txt"))
while ((line = file.ReadLine()) != null)
{
if (line.Contains(s1) || line.Contains(s2))
{
file2.WriteLine(line);
counter++;
}
}
file.Close();
And this is done by a single button. What I want though is to be able to search for the file I want and then use another button in order to do all writing process
Answer for the EDIT:
You can store the read data in property or private field in the form class. Use String or StringBuilder preferably. When the second button is clicked check if there is stored data and write it to the output file.
private StringBuilder data = new StringBuilder();
private void button2_Click(object sender, EventArgs e)
{
if(data.Length > 0)
{
using(System.IO.StreamWriter file2 = new System.IO.StreamWriter(#"D:\test.txt"))
{
file2.Write(data.ToString());
}
}
}
private void button1_Click(object sender, EventArgs e)
{
// Clear the previous store data
data.Clear();
// ...
System.IO.StreamReader file = new System.IO.StreamReader("d:\\license.txt");
while ((line = file.ReadLine()) != null)
{
if (line.Contains(s1) || line.Contains(s2))
{
sb.AppendLine(line);
counter++;
}
}
file.Close();
}
Please add using for System.IO and surround your StreamReader and StreamWriter with using block so your code will be more readable and you won't forget to release the used resources.
You can use StreamReader and StreamWriter for read/write file
To extract specific part of text, you may use Regex.Matches, it will return Match, then you can retrieve the defined group in Match.Groups
// Search name
Match mu = Regex.Match(line, #"Feature name: (\d+)");
// Get name
if (mu.Groups.Count == 1) Console.Writeline(mu.Groups[0].Value);

Formating txt file and displaying it to gridview

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.

C#: Storing the content of an ini file as string or dictionary instead of file name?

Is there a way to store the content of a file as string or as a dictionary instead of just its file path/name?
Below is the method that I am currently using for getting the file path from a Windows Form. Is there a way to adapt it or should I start from scratch? I am loading .ini files which is only text. LINQ seems to be one route but I am not familiar with it.
public void ShowSettingsGui()
{
System.Windows.Forms.OpenFileDialog ofd = new System.Windows.Forms.OpenFileDialog();
ofd.Multiselect = false;
ofd.Filter = "Data Sources (*.ini)|*.ini*|All Files|*.*";
if (ofd.ShowDialog() == DialogResult.OK)
{
string[] filePath = ofd.FileNames;
}
m_settings = Path.GetDirectoryName(ofd.FileName);
}
LINQ is indeed a nice way to do it: We simply convert the paths to a dictionary (where they become the keys). The values are determined by calling File.ReadAllText on every file path.
var dialog = new OpenFileDialog() { Multiselect = true,
Filter = "Data Sources (*.ini)|*.ini*|All Files|*.*" };
if (dialog.ShowDialog() != DialogResult.OK) return;
var paths = dialog.FileNames;
var fileContents = paths.ToDictionary(filePath => filePath, File.ReadAllText);
To help you understand what's going one here, take a look at the (roughly equivalent) non-LINQ version. Here, we explicitly iterate over the FileNames and add them as keys to our dictionary while again calling File.ReadAllText on every one of them.
// same as first snippet without the last line
foreach (var filePath in paths)
{
fileContents.Add(filePath, File.ReadAllText(filePath));
}
Set a breakpoint to the last line of each snippet, run them and take a look at the contents of the dictionary to determine the result.
EDIT: It wasn't clear in the question, but it seems you're only interested in a single file name. That means you don't need LINQ at all (m_settings needs to be a string).
var dialog = new OpenFileDialog{Filter = "Data Sources (*.ini)|*.ini*|All Files|*.*"};
if (dialog.ShowDialog() != DialogResult.OK) return;
m_settings = File.ReadAllText(dialog.FileName);
if you can add description of what are you trying to accomplish it would help.
just the same, I would use to store/read settings by using the settings class
here is a link to how to use it:
write user settings
I used in the past xml to parse a settings file, i find it much easier than reading ini in a sequential manner.
Hope it helps

Search and replace contents of text file based on mappings in CSV file in C#

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

Categories