Manually entering what to search for - c#

I have a program that manually loops through files in a folder and searches for keywords, telling you which file has them.
class Program
{
static void Main()
{
string input = "";
Console.WriteLine("Where? ");
input = Console.ReadLine();
LoopedData(input);
Console.ReadLine();
}
static void LoopedData(string path)
{
string[] files;
string[] directories;
string lineToFind = keyword;
files = Directory.GetFiles(path);
foreach (string file in files)
{
int line = 1;
using (var reader = new StreamReader(file))
{
// read file line by line
string lineRead;
while ((lineRead = reader.ReadLine()) != null)
{
if ( lineRead.Contains(lineToFind))
{
Console.WriteLine("File {0}, line: {1}", file, lineRead);
Console.ReadLine();
}
else
{
Console.WriteLine(" ");
}
line++;
}
}
Console.WriteLine("Finished.....");
Console.ReadLine();
//Console.WriteLine(file);
// look for string here
}
directories = Directory.GetDirectories(path);
foreach (string directory in directories)
{
// Process each directory recursively
LoopedData(directory);
}
}
}
I have been able to manually enter which folders to search in but I am having difficulty in creating a similar way to do it for the keyword. I have tried referencing it in the Main class, with no success. I need a fresh pair of eyes.
Any search I try doesn't yield helpful results

It seems you already know what to do. Your doing it correctly for the path. To get the keyword from the user, just do the same thing as for the path:
static void Main()
{
string path = "";
string keyword = "";
Console.WriteLine("Where? "); // read path
path = Console.ReadLine();
Console.WriteLine("What? "); // read keyword
keyword = Console.ReadLine();
LoopedData(input, keyword);
Console.ReadLine();
}
And change your LoopedData's signature like that to pass the keyword as parameter:
static void LoopedData(string path, string keywork)
{
// your code
}

Related

C# Reading Paths From Text File Says Path Doesn't Exist [duplicate]

This question already has answers here:
What's the fastest way to read a text file line-by-line?
(9 answers)
Closed 7 years ago.
I'm developing a small command line utility to remove files from a directory. The user has the option to specify a path at the command line or have the paths being read from a text file.
Here is a sample text input:
C:\Users\MrRobot\Desktop\Delete
C:\Users\MrRobot\Desktop\Erase
C:\Users\MrRobot\Desktop\Test
My Code:
class Program
{
public static void Main(string[] args)
{
Console.WriteLine("Number of command line parameters = {0}", args.Length);
if(args[0] == "-tpath:"){
clearPath(args[1]);
}
else
if(args[0] == "-treadtxt:"){
readFromText(args[1]);
}
}
public static void clearPath(string path)
{
if(Directory.Exists(path)){
int directoryCount = Directory.GetDirectories(path).Length;
if(directoryCount > 0){
DirectoryInfo di = new DirectoryInfo(path);
foreach (DirectoryInfo dir in di.GetDirectories())
{
dir.Delete(true);
}
}
else{
Console.WriteLine("No Subdirectories to Remove");
}
int fileCount = Directory.GetFiles(path).Length;
if(fileCount > 0){
System.IO.DirectoryInfo di = new DirectoryInfo(path);
foreach (FileInfo file in di.GetFiles())
{
file.Delete();
}
}
else{
Console.WriteLine("No Files to Remove");
}
}
else{
Console.WriteLine("Path Doesn't Exist {0}", path);
}
}
public static void readFromText(string pathtotext)
{
try
{ // Open the text file using a stream reader.
using (StreamReader sr = new StreamReader(pathtotext))
{
// Read the stream to a string, and write the string to the console.
string line = sr.ReadToEnd();
clearPath(line);
}
}
catch (Exception e)
{
Console.WriteLine("The file could not be read:");
Console.WriteLine(e.Message);
}
}
}
}
My Problem:
When reading from the text file, it says that the first path doesn't exist, and prints all the paths to the prompt, despite that I have no Console.WriteLine(). However, if I plug these same paths and call -tPath: it will work. My issue seems to be in the readFromText() I just can't seem to figure it out.
This is the problem:
string line = sr.ReadToEnd();
That isn't reading a line of data - it's reading the whole file in one go. Your clearPath method expects its parameter to be a single path, not a bunch of lines glued together. The reason you're seeing all the paths is that clearPath is being called (with everything in one call), that "glued together" path isn't being found, and it's printing out the input in Console.WriteLine("Path Doesn't Exist {0}", path);.
I suspect you should use something like:
var lines = File.ReadAllLines(pathtotext);
foreach (var line in lines)
{
clearPath(pathtotext);
}

Cannot read keys when either application does not have a console or when console input has been redirected from a file. Try Console.Read

Cannot get program to read the file, not sure what I'm doing wrong here, any advice is welcomed.
Trying to do a project for an address book and the file contains all the people's names and addresses and phone numbers.
public Form1()
{
string filename = "Addresses.txt";
ReadFile(filename);
ReadTokens(filename);
}//end of main
static void ReadFile(string filename)
{
StreamReader readFile;
readFile = File.OpenText(filename);
while (!readFile.EndOfStream)
{
Console.WriteLine(readFile.ReadLine());
}//end of while
{
readFile.Close();
Console.ReadKey();
}//End of read file
}
static void ReadTokens(string filename)
{
StreamReader readFile;
string line;
char[] delim = { ',' };
readFile = File.OpenText(filename);
while (!readFile.EndOfStream)
{
line = readFile.ReadLine(); // reads one line at a time
string[] tokens = line.Split(delim);
foreach (string str in tokens)
{
Console.WriteLine(str + "\t\t");
}//end of for each
}
Console.ReadKey();
readFile.Close();
}//end of ReadTokens
}//end of program
}//end namespace

File method with removing lines

I am working on a method that reads txt file with multiple lines and then turns it into a txt file with only single line.
Like this:
first line,
second line,
third line.
Into this:
first line, second line, third line.
I have this code but it only shows "third line." in file:
MAIN:
static void Main(string[] args)
{
string fLine= "first line,\n second line,\n third line.";
string sLine= "";
Console.Write(fLine);
Console.WriteLine();
Console.Write(sLine);
string filDat1 = "D:\\Dat1.txt";
string filDat2 = "D:\\Dat2.txt";
if (File.Exists(filDat1))
Console.WriteLine("File already exist!");
else
{
File.WriteAllText(filDat1, fLine);
}
File.WriteAllText(filDat2, sLine);
changeFile(filDat1);
Console.ReadKey();
}
METHOD:
public static void changeFile(string name)
{
StringBuilder dato;
string filDat2 = "D:\\Dat2.txt";
try
{
string[] lines = File.ReadAllLines(name);
foreach (string line in lines)
{
Console.WriteLine("Words in file: " + line);
}
Console.WriteLine();
Console.Write("New words in new file: ");
foreach (string line in lines)
{
string line1 = line;
dato = new StringBuilder();
line1 = line1.Replace("\n", " ");
for (int i = 0; i < line1.Count(); i++)
{
if (!line1[i].Equals(""))
{
dato.Append(line1[i] + "");
}
}
Console.WriteLine(dato);
File.WriteAllText(filDat2, dato.ToString());
}
}
I don't know what I'm doing wrong. I only get the last word in my case "third word." in new file Dat2.txt.
Also, is there any way to create a method that can take two files. One file to read and one file to write that changed text to it?
Here is a method to make anew file for given file with only 1 line:
public static void changeFile(string InputPath,string OutputPath)
{
List<string> OUTPUT = new List<string>();
StreamReader sr = new StreamReader(InputPath);
while (!sr.EndOfStream)
{
OUTPUT.Add(sr.ReadLine());
}
sr.Close();
StreamWriter fs = new StreamWriter(OutputPath);
string output = "";
foreach (string line in OUTPUT)
{
output += line + " ";
}
fs.WriteLine(output);
fs.Close();
}
In case you were curious as to why your approach didn't work, it was because you reset dato every iteration, just move that outside and away you go, I've also moved the write outside too since you only need to do that once.
dato = new StringBuilder();
foreach (string line in lines)
{
string line1 = line;
line1 = line1.Replace("\n", " ");
for (int i = 0; i < line1.Count(); i++)
{
if (!line1[i].Equals(""))
{
dato.Append(line1[i] + "");
}
}
Console.WriteLine(dato);
}
File.WriteAllText(filDat2, dato.ToString());

Replacing a certain word in a text file

I know this has been asked a few times, but I have seen a lot of regex etc., and I'm sure there is another way to do this with just a stream reader/writer. Below is my code. I'm trying to replace "tea" with the word "cabbage". Can somebody help? I believe I have the wrong syntax.
namespace Week_9_Exer_4
{
class TextImportEdit
{
public void EditorialControl()
{
string fileName;
string lineReadFromFile;
Console.WriteLine("");
// Ask for the name of the file to be read
Console.Write("Which file do you wish to read? ");
fileName = Console.ReadLine();
Console.WriteLine("");
// Open the file for reading
StreamReader fileReader = new StreamReader("C:\\Users\\Greg\\Desktop\\Programming Files\\story.txt");
// Read the lines from the file and display them
// until a null is returned (indicating end of file)
lineReadFromFile = fileReader.ReadLine();
Console.WriteLine("Please enter the word you wish to edit out: ");
string editWord = Console.ReadLine();
while (lineReadFromFile != null)
{
Console.WriteLine(lineReadFromFile);
lineReadFromFile = fileReader.ReadLine();
}
String text = File.ReadAllText("C:\\Users\\Greg\\Desktop\\Programming Files\\story.txt");
fileReader.Close();
StreamWriter fileWriter = new StreamWriter("C:\\Users\\Greg\\Desktop\\Programming Files\\story.txt", false);
string newText = text.Replace("tea", "cabbage");
fileWriter.WriteLine(newText);
fileWriter.Close();
}
}
}
If you don't care about memory usage:
string fileName = #"C:\Users\Greg\Desktop\Programming Files\story.txt";
File.WriteAllText(fileName, File.ReadAllText(fileName).Replace("tea", "cabbage"));
If you have a multi-line file that doesn't randomly split words at the end of the line, you could modify one line at a time in a more memory-friendly way:
// Open a stream for the source file
using (var sourceFile = File.OpenText(fileName))
{
// Create a temporary file path where we can write modify lines
string tempFile = Path.Combine(Path.GetDirectoryName(fileName), "story-temp.txt");
// Open a stream for the temporary file
using (var tempFileStream = new StreamWriter(tempFile))
{
string line;
// read lines while the file has them
while ((line = sourceFile.ReadLine()) != null)
{
// Do the word replacement
line = line.Replace("tea", "cabbage");
// Write the modified line to the new file
tempFileStream.WriteLine(line);
}
}
}
// Replace the original file with the temporary one
File.Replace("story-temp.txt", "story.txt", null);
In the end i used this : Hope it can help out others
public List<string> EditorialResponse(string fileName, string searchString, string replacementString)
{
List<string> list = new List<string>();
using (StreamReader reader = new StreamReader(fileName))
{
string line;
while ((line = reader.ReadLine()) != null)
{
line = line.Replace(searchString, replacementString);
list.Add(line);
Console.WriteLine(line);
}
reader.Close();
}
return list;
}
}
class Program
{
static void Main(string[] args)
{
TextImportEdit tie = new TextImportEdit();
List<string> ls = tie.EditorialResponse(#"C:\Users\Tom\Documents\Visual Studio 2013\story.txt", "tea", "cockrel");
StreamWriter writer = new StreamWriter(#"C:\Users\Tom\Documents\Visual Studio 2013\story12.txt");
foreach (string line in ls)
{
writer.WriteLine(line);
}
writer.Close();
}
}
}

C# Edit string in file - delete a character (000)

I am rookie in C#, but I need solve one Problem.
I have several text files in Folder and each text files has this structure:
IdNr 000000100
Name Name
Lastname Lastname
Sex M
.... etc...
Load all files from Folder, this is no Problem ,but i need delete "zero" in IdNr, so delete 000000 and 100 leave there. After this file save. Each files had other IdNr, Therefore, it is harder :(
Yes, it is possible each files manual edit, but when i have 3000 files, this is not good :)
Can C# one algorithm, which could this 000000 delete and leave only number 100?
Thank you All.
Vaclav
So, thank you ALL !
But in the End I have this Code :-) :
using System.IO;
namespace name
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Browse_Click(object sender, EventArgs e)
{
DialogResult dialog = folderBrowserDialog1.ShowDialog();
if (dialog == DialogResult.OK)
TP_zdroj.Text = folderBrowserDialog1.SelectedPath;
}
private void start_Click(object sender, EventArgs e)
{
try
{
foreach (string file in Directory.GetFiles(TP_zdroj.Text, "*.txt"))
{
string text = File.ReadAllText(file, Encoding.Default);
text = System.Text.RegularExpressions.Regex.Replace(text, "IdNr 000*", "IdNr ");
File.WriteAllText(file, text, Encoding.Default);
}
}
catch
{
MessageBox.Show("Warning...!");
return;
}
{
MessageBox.Show("Done");
}
}
}
}
Thank you ALL ! ;)
You can use int.Parse:
int number = int.Parse("000000100");
String withoutzeros = number.ToString();
According to your read/save file issue, do the files contain more than one record, is that the header or does each record is a list of key and value like "IdNr 000000100"? It's difficult to answer without these informations.
Edit: Here's a simple but efficient approach which should work if the format is strict:
var files = Directory.EnumerateFiles(path, "*.txt", SearchOption.TopDirectoryOnly);
foreach (var fPath in files)
{
String[] oldLines = File.ReadAllLines(fPath); // load into memory is faster when the files are not really huge
String key = "IdNr ";
if (oldLines.Length != 0)
{
IList<String> newLines = new List<String>();
foreach (String line in oldLines)
{
String newLine = line;
if (line.Contains(key))
{
int numberRangeStart = line.IndexOf(key) + key.Length;
int numberRangeEnd = line.IndexOf(" ", numberRangeStart);
String numberStr = line.Substring(numberRangeStart, numberRangeEnd - numberRangeStart);
int number = int.Parse(numberStr);
String withoutZeros = number.ToString();
newLine = line.Replace(key + numberStr, key + withoutZeros);
newLines.Add(line);
}
newLines.Add(newLine);
}
File.WriteAllLines(fPath, newLines);
}
}
Use TrimStart
var trimmedText = number.TrimStart('0');
This should do it. It assumes your files have a .txt extension, and it removes all occurrences of "000000" from each file.
foreach (string fileName in Directory.GetFiles("*.txt"))
{
File.WriteAllText(fileName, File.ReadAllText(fileName).Replace("000000", ""));
}
These are the steps you would want to take:
Loop each file
Read file line by line
for each line split on " " and remove leading zeros from 2nd element
write the new line back to a temp file
after all lines processed, delete original file and rename temp file
do next file
(you can avoid the temp file part by reading each file in full into memory, but depending on your file sizes this may not be practical)
You can remove the leading zeros with something like this:
string s = "000000100";
s = s.TrimStart('0');
Simply, read every token from the file and use this method:
var token = "000000100";
var result = token.TrimStart('0');
You can write a function similar to this one:
static IEnumerable<string> ModifiedLines(string file) {
string line;
using(var reader = File.OpenText(file)) {
while((line = reader.ReadLine()) != null) {
string[] tokens = line.Split(new char[] { ' ' });
line = string.Empty;
foreach (var token in tokens)
{
line += token.TrimStart('0') + " ";
}
yield return line;
}
}
}
Usage:
File.WriteAllLines(file, ModifiedLines(file));

Categories