Sounds overly complex, no reason to check by line or anything if you want to know if a string is present in a file. You can replace all of your code simply with :
if (File.ReadAllText(path).Contains(domain)) {
MessageBox.Show("There is a match");
}
I would recommend seting and flag and checking it as follows...
using(StreamReader sr = File.OpenText(path)) {
string[] lines = File.ReadAllLines(path);
bool isMatch = false;
for (int x = 0; x < lines.Length - 1; x++) {
if (domain == lines[x]) {
sr.Close();
MessageBox.Show("there is a match");
isMatch = true;
}
}
if (!isMatch) {
sr.Close();
MessageBox.Show("there is no match");
}
}
Actually you don't need to read whole file into memory. There is File.ReadLines method which allows you enumerate file lines one by one, without reading whole file. You can create following method
private bool DomainExists(string domain) {
foreach(string line in File.ReadLines(path))
if (domain == line)
return true; // and stop reading lines
return false;
}
Usage of this method looks like:
if (DomainExists(domain))
MessageBox.Show("there is a match");
else
MessageBox.Show("there is no match");
Simplest way:
string content = File.ReadAllText(path);
if (content.IndexOf(domain) > -1) {
// domain exists
} else {
// domain does not exist
}
2nd, what if domain name has multiple occurrence in the file? In your code you will get multiple 'there is a match' in your code.
using(StreamReader sr = File.OpenText(path)) // you can remove this line
{
string[] lines = File.ReadAllLines(path); // as you are not using it here
for (int x = 0; x < lines.Length - 1; x++) {
if (domain == lines[x]) {
sr.Close();
MessageBox.Show("there is a match");
hasMatch = true;
break; // exit loop if found
}
}
if (!hasMatch) {
// there is no match
}
if (sr != null) // you dont need this if you remove it from the beginning of the code
{
sr.Close();
MessageBox.Show("there is no match");
}
}
First you need to create a method that receives an array of type string, then we convert that array to a string, then we read all the text from the txt and we can use (Contains) to know if the text we send exists in our txt and we validate if that is truth or false, I hope it helps you.
public static void TextValidation(string[] val) {
//Path of your file
string path = "/Users/Desktop/YourFile.txt";
//Array to string
string b = string.Join(",", val);
//Validate if exists
if (File.ReadAllText(path).Contains(b)) {
Console.WriteLine("found");
// Do something if the data is found
} else {
Console.WriteLine("Not found");
}
}
Due to the accepted answer not fixing the problems in the original question here is a short and sweet LINQ based version:
private static bool TextFoundInFile(string fileName, string text) {
// If the line contains the text, FirstOrDefault will return it.
// Null means we reached the end without finding it.
return File.ReadLines(fileName).FirstOrDefault(x => x.Contains(text)) is not null;
}
I have a request, to check for a specific word in a text file "Successfully" which should return value ok or not ok.,I managed to do this but it is returning value "There isn't" everytime and i manually check the file do contains the word "Successfully",Just know, if the word "success" is found anywhere in this file it'll return "success" - hopefully you won't get bad info with this type of search.,You're getting a "There ins't!" return because you're looking for "Successfully" against $OCSFile which is just a file name.ย You're not reading the contents of said file.
$SEL = Select - String - Path 'C:\xxxx\Programs\OCS_Inventory\log\OCS_inventory_*.txt' - Pattern "Successfully"
if ($SEL - ne $null) {
Write - Host "Good"
} else {
Write - Host "Bad"
}
$dir = 'C:\temp\' $OCSlatest = (Get - ChildItem - Path $dir - Filter 'OCS_inventory_*.log' | Sort - Object LastCreatedTime - Descending | Select - Object - First 1).fullname if ($OCSlatest) { #we know we have a file $OCSlatest $search = (Get - Content $OCSlatest | Select - String - Pattern 'success').Matches.Success if ($search) { "Success" } else { "Fail" } } else { "No matching files found in $dir" }
$dir = 'C:\linkbynet\Programs\OCS_Inventory\log\OCS_inventory_*'
$latest = Get - ChildItem - Path $dir | Sort - Object LastCreatedTime - Descending | Select - Object - First 1
$OCSFile = $latest.name
Write - Host "Last File is "
$OCSFile
$OCSFile = $OCSFile | % {
$_ - contains 'Successfully'
}
if ($OCSFile - contains $true) {
Write - Host "There is!"
} else {
Write - Host "There ins't!"
}
$SEL = Get - Content - Path 'C:\xxxx\Programs\OCS_Inventory\log\OCS_inventory_*.txt' |
Select String - Pattern "Successfully"
if ($SEL - ne $null) {
Write - Host "Good"
} else {
Write - Host "Bad"
}
Last updated: Mar 28, 2022
Copied!// ๐๏ธ if using ES6 Imports
// import {readFileSync, promises as fsPromises} from 'fs';
const {readFileSync, promises: fsPromises} = require('fs');
// โ
read file SYNCHRONOUSLY
function checkIfContainsSync(filename, str) {
const contents = readFileSync(filename, 'utf-8');
const result = contents.includes(str);
return result;
}
// ๐๏ธ true
console.log(checkIfContainsSync('./example.txt', 'hello'));
// --------------------------------------------------------------
// โ
read file ASYNCHRONOUSLY
async function checkIfContainsAsync(filename, str) {
try {
const contents = await fsPromises.readFile(filename, 'utf-8');
const result = contents.includes(str);
console.log(result);
return result;
} catch (err) {
console.log(err);
}
}
// ๐๏ธ Promise<true>
checkIfContainsAsync('./example.txt', 'hello');
Copied! // ๐๏ธ if using ES6 Imports
// import {readFileSync, promises as fsPromises} from 'fs';
const {
readFileSync,
promises: fsPromises
} = require('fs');
// โ
read file SYNCHRONOUSLY
function checkIfContainsSync(filename, str) {
const contents = readFileSync(filename, 'utf-8');
// ๐๏ธ convert both to lowercase for case insensitive check
const result = contents.toLowerCase().includes(str.toLowerCase());
return result;
}
// ๐๏ธ true
console.log(checkIfContainsSync('./example.txt', 'HELLO'));
Copied!hello world one two three
Copied! // ๐๏ธ if using ES6 Imports
// import {readFileSync, promises as fsPromises} from 'fs';
const {
readFileSync,
promises: fsPromises
} = require('fs');
// โ
read file ASYNCHRONOUSLY
async function checkIfContainsAsync(filename, str) {
try {
const contents = await fsPromises.readFile(filename, 'utf-8');
const result = contents.includes(str);
console.log(result);
return result;
} catch (err) {
console.log(err);
}
}
checkIfContainsAsync('./example.txt', 'hello');
If the file exists, the exists() function returns True. Otherwise, it returns False.,If the file is in the same folder as the program, the path_to_file is just simply the file name.,If the file doesnโt exist, the is_file() method returns False. Otherwise, it returns True.,The following example uses the exists() function to check if the readme.txt file exists in the same folder as the program:
os.path.exists() function
.wp - block - code {
border: 0;
padding: 0;
}
.wp - block - code > div {
overflow: auto;
}
.shcb - language {
border: 0;
clip: rect(1 px, 1 px, 1 px, 1 px); -
webkit - clip - path: inset(50 % );
clip - path: inset(50 % );
height: 1 px;
margin: -1 px;
overflow: hidden;
padding: 0;
position: absolute;
width: 1 px;
word - wrap: normal;
word - break: normal;
}
.hljs {
box - sizing: border - box;
}
.hljs.shcb - code - table {
display: table;
width: 100 % ;
}
.hljs.shcb - code - table > .shcb - loc {
color: inherit;
display: table - row;
width: 100 % ;
}
.hljs.shcb - code - table.shcb - loc > span {
display: table - cell;
}
.wp - block - code code.hljs: not(.shcb - wrap - lines) {
white - space: pre;
}
.wp - block - code code.hljs.shcb - wrap - lines {
white - space: pre - wrap;
}
.hljs.shcb - line - numbers {
border - spacing: 0;
counter - reset: line;
}
.hljs.shcb - line - numbers > .shcb - loc {
counter - increment: line;
}
.hljs.shcb - line - numbers.shcb - loc > span {
padding - left: 0.75 em;
}
.hljs.shcb - line - numbers.shcb - loc::before {
border - right: 1 px solid #ddd;
content: counter(line);
display: table - cell;
padding: 0 0.75 em;
text - align: right; -
webkit - user - select: none; -
moz - user - select: none; -
ms - user - select: none;
user - select: none;
white - space: nowrap;
width: 1 % ;
}
from os.path
import exists
file_exists = exists(path_to_file) Code language: JavaScript(javascript)
Path.is_file() method
from pathlib
import Path
path = Path(path_to_file)
path.is_file() Code language: JavaScript(javascript)
First, import the os.path
standard library:
import os.pathCode language: JavaScript(javascript)
However, itโs not the case, you need to pass the full file path of the file. For example:
/path/to / filename
The following example uses the exists()
function to check if the readme.txt
file exists in the same folder as the program:
import os.path
file_exists = os.path.exists('readme.txt')
print(file_exists) Code language: JavaScript(javascript)