I have a string that is args[0]
.
Here is my code so far:
static void Main(string[] args) { string latestversion = args[0]; // create reader & open file using (StreamReader sr = new StreamReader("C:\\Work\\list.txt")) { while (sr.Peek() >= 0) { // code here } } }
I would like to check if my list.txt
file contains args[0]
. If it does, then I will create another process StreamWriter
to write a string 1
or 0
into the file. How do I do this?
Contains() Method. In C#, String. Contains() is a string method. This method is used to check whether the substring occurs within a given string or not.
Open(FileMode. OpenOrCreate, FileAccess. Read , FileShare. Read); //Create an object of StreamReader by passing FileStream object on which it needs to operates on StreamReader sr = new StreamReader(fs); //Use the ReadToEnd method to read all the content from file string fileContent = sr.
Are you expecting the file to be particularly big? If not, the simplest way of doing it would be to just read the whole thing:
using (StreamReader sr = new StreamReader("C:\\Work\\list.txt")) { string contents = sr.ReadToEnd(); if (contents.Contains(args[0])) { // ... } }
Or:
string contents = File.ReadAllText("C:\\Work\\list.txt"); if (contents.Contains(args[0])) { // ... }
Alternatively, you could read it line by line:
foreach (string line in File.ReadLines("C:\\Work\\list.txt")) { if (line.Contains(args[0])) { // ... // Break if you don't need to do anything else } }
Or even more LINQ-like:
if (File.ReadLines("C:\\Work\\list.txt").Any(line => line.Contains(args[0]))) { ... }
Note that ReadLines
is only available from .NET 4, but you could reasonably easily call TextReader.ReadLine
in a loop yourself instead.
Code to work:
string latestversion = args[0]; using (StreamReader sr = new StreamReader("C:\\Work\\list.txt")) using (StreamWriter sw = new StreamWriter("C:\\Work\\otherFile.txt")) { // loop by lines - for big files string line = sr.ReadLine(); bool flag = false; while (line != null) { if (line.IndexOf(latestversion) > -1) { flag = true; break; } line = sr.ReadLine(); } if (flag) sw.Write("1"); else sw.Write("0"); // other solution - for small files var fileContents = sr.ReadToEnd(); { if (fileContents.IndexOf(latestversion) > -1) sw.Write("1"); else sw.Write("0"); } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With