Reading Text from Comma-Delimited file - c#

I have the following text file called urlmap.txt in App_Data
ShowProduct.aspx?ID=1143, laptops/1143/laptops-for-beginner-experienced-engineers
ShowProduct.aspx?ID=1142, desktops/1142/dynamic-difference-desktops
ShowProduct.aspx?ID=1141, keyboards/1141/bluetooth-ready-keyboards
ShowProduct.aspx?ID=1140, mouse/1140/microsoft-2key-mouse-with-pad
ShowProduct.aspx?ID=1139, mouse/1139/logitech-3key-mouse-auto-shutoff
and about 2000 such entries....
I want to pass in a string like "ShowProduct.aspx?ID=1140" and search and retrieve the text in front of it i.e. "mouse/1140/microsoft-2key-mouse-with-pad"
If this string is not found, it retrieves nothing.
Each string in urlmap.txt is unique, so there is no chance of duplication
How can I do this?
This is what I have so far but I am unable to determine how to retreive the text in front of it
string line;
StringBuilder sb = new StringBuilder();
using (System.IO.StreamReader file = new System.IO.StreamReader("App_Data\urlmap.txt"))
{
while ((line = file.ReadLine()) != null)
{
if (line.Contains(mySearchString))
{
}
}
}
Since the text file contains about 2000+lines, I also need an optimized way of retrieving the record.

Just use Split:
if (line.Contains(mySearchString))
{
var text = line.Split(",")[1];
/*do something else with text*/
}

Related

C# WPF How do I display the contents of a .txt file into a list box?

Say I have a txt file with this content:
Tom, 11
Jason, 12
Gary, 13
Ted, 14
The WPF is just a list box.
What would I need to do for the list box, to show the names inside the txt file when I start the program.
This is a very simple question, but I cant figure it out. I don't know where the txt file needs to be saved and I don't know how to call it in the ".cs"
This is code which read next line to list,then read how to add this to listbox
List<string> lines = new List<string>();
using (StreamReader r = new StreamReader(f))
{
string line;
while ((line = r.ReadLine()) != null)
{
lines.Add(line);
}
}
This is example how to binding list to listbox:
eventList.ItemsSource = lines;
Text file can be anywhere as you can specify path to it while opening. You can put it inside solution folder to make path shorter.
Then in main method you write something like
var MyList = new List<string>();
using (var streamReader = File.OpenText(pathToYourTextFile))
{
var s = string.Empty;
while ((s = streamReader.ReadLine()) != null)
MyList.Add(s);
}
myListbox.ItemsSource = MyList;

Search for a file content in c#

Hi I'm writing a c# code where in there is a string sent as a parameter input to the method. And then the inputString has to be searched in the file and the result has to be returned. Currently I know how do I do this in the regular way(using the file IO).
[HttpPost]
public string UsernameValidation(string username)
{
string text = username;
string userExists = usernameNotAvailable;
string line;
System.IO.StreamReader file = new System.IO.StreamReader("~/UserData/usernameslist.txt");
while ((line = file.ReadLine()) != null)
{
if (line.Contains(text))
{
userExists = usernameAvailable;
}
}
return userExists;
}
But here is the twist, my project is in MVC. I'm able to get the path of file using string userDataFile = Server.MapPath("~/UserData/usernameslist.txt");.
But I'm unable to know how can I get the functionality of searching a string in a file.
Please let me know how can I do this.
Thanks
If the the file usernameslist.txt really exists inside a subfolder named UserData from your root folder then you just need to pass the output of Server.MapPath to your StreamReader constructor
string fileName = Server.MapPath("~/UserData/usernameslist.txt");
using(StreamReader file = new System.IO.StreamReader(fileName))
{
....
}
And don't forget to use the using statement around a Stream object

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

C# listbox split to another 2 listboxes

Problem:
I have 1 ListBox which loads a text file contain:
ip:port
ip:port
ip:port
What I want to do is, once I've loaded the text file into the list box, I want to have the 'ip' to go into a different listbox and the 'port' into a different listbox. This is first time working on a project like this.
// if you wanted to do it with LINQ.
// of course you're loading all lines
// into memory at once here of which
// you'd have to do regardless
var text = File.ReadAllLines("TestFile.txt");
var ipsAndPorts = text.Select(l => l.Split(':')).ToList();
ipsAndPorts.ForEach(ipAndPort =>
{
lstBoxIp.Items.Add(ipAndPort[0]);
lstBoxPort.Items.Add(ipAndPort[1]);
});
Something like
using (StreamReader sr = new StreamReader("TestFile.txt"))
{
String line;
// Read and display lines from the file until the end of
// the file is reached.
while ((line = sr.ReadLine()) != null)
{
string[] ipandport = line.split(":");
lstBoxIp.Items.Add( ipandport[0] );
lstBoxPort.Items.Add( ipandport[1] );
}
}

C# method to read text error log file

I am trying to read a file I create that contains all the logs lines throughout my program. I have the following cod:
private string ReadEmailLog(string EmailLog)
{
TextReader tr = new StreamReader(EmailLog);
tr.ReadLine();
tr.Close();
}
I need to read the EmailLog file, every line of it, and then put return it into a string called message. How would I get this method to return the whole log file, every line?
You can use File.ReadAllText or File.ReadAllLines.
If you're using .NET 4.0, you can also use File.ReadLines:
var files = from file in Directory.EnumerateFiles(#"c:\",
"*.txt", SearchOption.AllDirectories)
from line in File.ReadLines(file)
where line.Contains("Microsoft")
select new
{
File = file,
Line = line
};
foreach (var f in files)
{
Console.WriteLine("{0}\t{1}", f.File, f.Line);
}
This allows you to make file I/O part of a LINQ operation.
Try
tr.ReadToEnd();
which will return a string that contains all the content of your file.
TextReader.ReadToEnd Method
If you want to get the lines in a string[], then
tr.ReadToEnd().Split("\n");
should do it, while it will separate the lines to the "\n" character, which represents a carriage return and line feed combined characters (new line character).
simply use:
String text = tr.ReadToEnd();
You can read all the contents or the log and return it. For example:
private string void ReadEmailLog(string EmailLog)
{
using(StreamReader logreader = new StreamReader(EmailLog))
{
return logreader.ReadToEnd();
}
}
Or if you want each line one at a time:
private IEnumerable<string> ReadEmailLogLines(string EmailLog)
{
using(StreamReader logreader = new StreamReader(EmailLog))
{
string line = logreader.ReadLine();
while(line != null)
{
yield return line;
}
}
}
tr.ReadToEnd(); //read whole file at once
// or line by line
While ( ! tr.EOF)
tr.ReadLine()//

Categories