C# text file browse and file write - c#

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

Related

Empty file saved after stream object write line command [duplicate]

There are a lot of different ways to read and write files (text files, not binary) in C#.
I just need something that is easy and uses the least amount of code, because I am going to be working with files a lot in my project. I only need something for string since all I need is to read and write strings.
Use File.ReadAllText and File.WriteAllText.
MSDN example excerpt:
// Create a file to write to.
string createText = "Hello and Welcome" + Environment.NewLine;
File.WriteAllText(path, createText);
...
// Open the file to read from.
string readText = File.ReadAllText(path);
In addition to File.ReadAllText, File.ReadAllLines, and File.WriteAllText (and similar helpers from File class) shown in another answer you can use StreamWriter/StreamReader classes.
Writing a text file:
using(StreamWriter writetext = new StreamWriter("write.txt"))
{
writetext.WriteLine("writing in text file");
}
Reading a text file:
using(StreamReader readtext = new StreamReader("readme.txt"))
{
string readText = readtext.ReadLine();
}
Notes:
You can use readtext.Dispose() instead of using, but it will not close file/reader/writer in case of exceptions
Be aware that relative path is relative to current working directory. You may want to use/construct absolute path.
Missing using/Close is very common reason of "why data is not written to file".
FileStream fs = new FileStream(txtSourcePath.Text,FileMode.Open, FileAccess.Read);
using(StreamReader sr = new StreamReader(fs))
{
using (StreamWriter sw = new StreamWriter(Destination))
{
sw.Writeline("Your text");
}
}
The easiest way to read from a file and write to a file:
//Read from a file
string something = File.ReadAllText("C:\\Rfile.txt");
//Write to a file
using (StreamWriter writer = new StreamWriter("Wfile.txt"))
{
writer.WriteLine(something);
}
using (var file = File.Create("pricequote.txt"))
{
...........
}
using (var file = File.OpenRead("pricequote.txt"))
{
..........
}
Simple, easy and also disposes/cleans up the object once you are done with it.
#AlexeiLevenkov pointed me at another "easiest way" namely the extension method. It takes just a little coding, then provides the absolute easiest way to read/write, plus it offers the flexibility to create variations according to your personal needs. Here is a complete example:
This defines the extension method on the string type. Note that the only thing that really matters is the function argument with extra keyword this, that makes it refer to the object that the method is attached to. The class name does not matter; the class and method must be declared static.
using System.IO;//File, Directory, Path
namespace Lib
{
/// <summary>
/// Handy string methods
/// </summary>
public static class Strings
{
/// <summary>
/// Extension method to write the string Str to a file
/// </summary>
/// <param name="Str"></param>
/// <param name="Filename"></param>
public static void WriteToFile(this string Str, string Filename)
{
File.WriteAllText(Filename, Str);
return;
}
// of course you could add other useful string methods...
}//end class
}//end ns
This is how to use the string extension method, note that it refers automagically to the class Strings:
using Lib;//(extension) method(s) for string
namespace ConsoleApp_Sandbox
{
class Program
{
static void Main(string[] args)
{
"Hello World!".WriteToFile(#"c:\temp\helloworld.txt");
return;
}
}//end class
}//end ns
I would never have found this myself, but it works great, so I wanted to share this. Have fun!
These are the best and most commonly used methods for writing to and reading from files:
using System.IO;
File.AppendAllText(sFilePathAndName, sTextToWrite);//add text to existing file
File.WriteAllText(sFilePathAndName, sTextToWrite);//will overwrite the text in the existing file. If the file doesn't exist, it will create it.
File.ReadAllText(sFilePathAndName);
The old way, which I was taught in college was to use stream reader/stream writer, but the File I/O methods are less clunky and require fewer lines of code. You can type in "File." in your IDE (make sure you include the System.IO import statement) and see all the methods available. Below are example methods for reading/writing strings to/from text files (.txt.) using a Windows Forms App.
Append text to an existing file:
private void AppendTextToExistingFile_Click(object sender, EventArgs e)
{
string sTextToAppend = txtMainUserInput.Text;
//first, check to make sure that the user entered something in the text box.
if (sTextToAppend == "" || sTextToAppend == null)
{MessageBox.Show("You did not enter any text. Please try again");}
else
{
string sFilePathAndName = getFileNameFromUser();// opens the file dailog; user selects a file (.txt filter) and the method returns a path\filename.txt as string.
if (sFilePathAndName == "" || sFilePathAndName == null)
{
//MessageBox.Show("You cancalled"); //DO NOTHING
}
else
{
sTextToAppend = ("\r\n" + sTextToAppend);//create a new line for the new text
File.AppendAllText(sFilePathAndName, sTextToAppend);
string sFileNameOnly = sFilePathAndName.Substring(sFilePathAndName.LastIndexOf('\\') + 1);
MessageBox.Show("Your new text has been appended to " + sFileNameOnly);
}//end nested if/else
}//end if/else
}//end method AppendTextToExistingFile_Click
Get file name from the user via file explorer/open file dialog (you will need this to select existing files).
private string getFileNameFromUser()//returns file path\name
{
string sFileNameAndPath = "";
OpenFileDialog fd = new OpenFileDialog();
fd.Title = "Select file";
fd.Filter = "TXT files|*.txt";
fd.InitialDirectory = Environment.CurrentDirectory;
if (fd.ShowDialog() == DialogResult.OK)
{
sFileNameAndPath = (fd.FileName.ToString());
}
return sFileNameAndPath;
}//end method getFileNameFromUser
Get text from an existing file:
private void btnGetTextFromExistingFile_Click(object sender, EventArgs e)
{
string sFileNameAndPath = getFileNameFromUser();
txtMainUserInput.Text = File.ReadAllText(sFileNameAndPath); //display the text
}
Or, if you are really about lines:
System.IO.File also contains a static method WriteAllLines, so you could do:
IList<string> myLines = new List<string>()
{
"line1",
"line2",
"line3",
};
File.WriteAllLines("./foo", myLines);
It's good when reading to use the OpenFileDialog control to browse to any file you want to read. Find the code below:
Don't forget to add the following using statement to read files: using System.IO;
private void button1_Click(object sender, EventArgs e)
{
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
textBox1.Text = File.ReadAllText(openFileDialog1.FileName);
}
}
To write files you can use the method File.WriteAllText.
class Program
{
public static void Main()
{
//To write in a txt file
File.WriteAllText("C:\\Users\\HP\\Desktop\\c#file.txt", "Hello and Welcome");
//To Read from a txt file & print on console
string copyTxt = File.ReadAllText("C:\\Users\\HP\\Desktop\\c#file.txt");
Console.Out.WriteLine("{0}",copyTxt);
}
}
private void Form1_Load(object sender, EventArgs e)
{
//Write a file
string text = "The text inside the file.";
System.IO.File.WriteAllText("file_name.txt", text);
//Read a file
string read = System.IO.File.ReadAllText("file_name.txt");
MessageBox.Show(read); //Display text in the file
}
Reading from file
string filePath = #"YOUR PATH";
List<string> lines = File.ReadAllLines(filePath).ToList();
Writing to file
List<string> lines = new List<string>();
string a = "Something to be written"
lines.Add(a);
File.WriteAllLines(filePath, lines);
Simply:
String inputText = "Hello World!";
File.WriteAllText("yourfile.ext",inputText); //writing
var outputText = File.ReadAllText("yourfile.ext"); //reading
You're looking for the File, StreamWriter, and StreamReader classes.

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

Load Config file into Windows Forms

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!

Reading of particular line of text file in WP7 based on some starting string and replacing (overwriting) it

I am able to do read/write/append operation on text file storing in isolated storage in WP7 application.
My scenario is that I am storing space seperated values in text file inside isolated storage.
So if I have to find for some particular line having some starting key then how to overwrite
value for that key without affecting the other line before and after it.
Example:
Key Value SomeOtherValue
*status read good
status1 unread bad
status2 null cantsay*
So if I have to change the whole second line based on some condition with key as same
status1 read good
How can I achieve this?
There are a number of ways you could do this, and the method you choose should be best suited to the size and complexity of the data file.
One option to get you started is to use the static string.Replace() method. This is crude, but if your file is only small then there is nothing wrong with it.
class Program
{
static void Main(string[] args)
{
StringBuilder sb = new StringBuilder();
sb.AppendLine("*status read good");
sb.AppendLine("status1 unread bad");
sb.AppendLine("status2 null cantsay*");
string input = sb.ToString();
var startPos = input.IndexOf("status1");
var endPos = input.IndexOf(Environment.NewLine, startPos);
var modifiedInput = input.Replace(oneLine.Substring(startPos, endPos - startPos), "status1 read good");
Console.WriteLine(modifiedInput);
Console.ReadKey();
}
}
If you store this information in text files then there won't be a way around replacing whole files. The following code does exactly this and might even be what you are doing right now.
// replace a given line in a given text file with a given replacement line
private void ReplaceLine(string fileName, int lineNrToBeReplaced, string newLine)
{
using (IsolatedStorageFile isf = IsolatedStorageFile.GetUserStoreForApplication())
{
// the memory writer will hold the read and modified lines
using (StreamWriter memWriter = new StreamWriter(new MemoryStream()))
{
// this is for reading lines from the source file
using (StreamReader fileReader = new StreamReader(new IsolatedStorageFileStream(fileName, System.IO.FileMode.Open, isf)))
{
int lineCount = 0;
// iterate file and read lines
while (!fileReader.EndOfStream)
{
string line = fileReader.ReadLine();
// check if this is the line which should be replaced; check is done by line
// number but could also be based on content
if (lineCount++ != lineNrToBeReplaced)
{
// just copy line from file
memWriter.WriteLine(line);
}
else
{
// replace line from file
memWriter.WriteLine(newLine);
}
}
}
memWriter.Flush();
memWriter.BaseStream.Position = 0;
// re-create file and save all lines from memory to this file
using (IsolatedStorageFileStream fileStream = new IsolatedStorageFileStream(fileName, System.IO.FileMode.Create, isf))
{
memWriter.BaseStream.CopyTo(fileStream);
}
}
}
}
private void button1_Click(object sender, RoutedEventArgs e)
{
ReplaceLine("test.txt", 1, "status1 read good");
}
And I agree with slugster: using SQLCE database might be a solution with better performance.

How to transform array into textfile?

I am currently creating a windows phone 7 application. How do I transform all the values of an array to textfile so I can print out all the values stored in that particular array inside another page listbox, and then store inside an isolated storage.
Thanks! :(
I tried this method but it doesn't work.
For ViewList.xaml.cs
private void addListBtn_Click(object sender, RoutedEventArgs e)
{
//Obtain the virtual store for application
IsolatedStorageFile myStore = IsolatedStorageFile.GetUserStoreForApplication();
//Create a new folder and call it "ImageFolder"
myStore.CreateDirectory("ListFolder");
//Create a new file and assign a StreamWriter to the store and this new file (myFile.txt)
//Also take the text contents from the txtWrite control and write it to myFile.txt
StreamWriter writeFile = new StreamWriter(new IsolatedStorageFileStream("ListFolder\\myFile.txt", FileMode.OpenOrCreate, myStore));
writeFile.WriteLine(retrieveDrinksListBox);
writeFile.Close();
}
FavouriteList.xaml.cs
private void PhoneApplicationPage_Loaded(object sender, RoutedEventArgs e)
{
//Obtain a virtual store for application
IsolatedStorageFile myStore = IsolatedStorageFile.GetUserStoreForApplication();
//This code will open and read the contents of retrieveDrinksListBox
//Add exception in case the user attempts to click “Read button first.
StreamReader readFile = null;
try
{
readFile = new StreamReader(new IsolatedStorageFileStream("ListFolder\\myFile.txt", FileMode.Open, myStore));
string fileText = readFile.ReadLine();
if (fileText != "")
{
listNumberListBox.Items.Add("List 1");
}
//The control txtRead will display the text entered in the file
listNumberListBox.Items.Add(fileText);
readFile.Close();
}
catch
{
MessageBox.Show("Need to create directory and the file first.");
}
You must write away the serialized items/data of the listbox, not the listbox itself.
When reading them again, you must deserialize them.The BinaryFormatter example on MSDN has code samples showing you how to write away an object to a (file)stream and how to recover the object again from that same stream.
If you want to display contents of your file (say, lines) in listbox, read entire file content at once and split the lines:
string fileText = readFile.ReadToEnd();
string[] lines = fileText.Split(Enviroment.NewLine.ToCharArray(),
StringSplitOptions.RemoveEmptyEntries);
listNumberListBox.Items.AddRange(lines);
Other way around is similar, fetch items from your listbox, by joining them with new line, and dump at once to file:
string fileContents = string.Join(Environment.NewLine,
retrieveDrinksListBox.Items.Cast<string>());
writeFile.WriteLine(fileContents);

Categories