How to add a new unique string to text file - c#

I have a text file contains several lines with words, for example like this
cards
door
lounge
dog
window
I want to add a new word into that list with the condition that it does not already exist in the list. For example I want to add wind or car
I use File.ReadAllText(#"C:\Temp.txt").Contains(word)
But the problem is window contains wind and cards contain car
Is there any way to compare it uniquely?

If you have not a huge file, you can read it to memory and process it like any array:
var lines = File.ReadAllLines(#"C:\Temp.txt");
if(lines.Any(x=>x == word)
{
//There is a word in the file
}
else
{
//Thee is no word in the file
}

Use File.ReadLine() and check for with String.equals(), dont look for substrings. Something Like this:
while(!reader.EndOfFile0
{
if(String.Compare(reader.ReadLine(),inputString, true) == 0)
{
//do your stuf here
}
}

You should do through Regex match so that you are matching an exact work, and I have made this below as case insensitive.
using ConsoleApplication3;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text.RegularExpressions;
public static class Program
{
private static void Main(string[] args)
{
// Read the file and display it line by line.
System.IO.StreamReader file =
new System.IO.StreamReader("c:\\temp\\test.txt");
var line = string.Empty;
string fileData = file.ReadToEnd();
file.Close();
fileData = "newword".InsertSkip(fileData);
StreamWriter fileWrite = new StreamWriter(#"C:\temp\test.txt", false);
fileWrite.Write(fileData);
fileWrite.Flush();
fileWrite.Close();
}
public static string InsertSkip(this string word, string data)
{
var regMatch = #"\b(" + word + #")\b";
Match result = Regex.Match(data, regMatch, RegexOptions.Singleline | RegexOptions.IgnoreCase);
if (result == null || result.Length == 0)
{
data += Environment.NewLine + word;
}
return data;
}
}
Although I am reading an entire file and writing an entire file back. You can improve the performance by only writing one word rather a whole file again.

you can do something like
string newWord = "your new word";
string textFile = System.IO.File.ReadAllText("text file full path");
if (!textFile.Contains(newWord))
{
textFile = textFile + newWord;
System.IO.File.WriteAllText("text file full path",textFile);
}

Related

Out of memory in LineReader

I am making a program that reads a .tyd file and tries to translate all the text between the " from English to Italian.
GoToDesk translate-> "Looking for computer"
The problem is that I am still getting "Out of memory".
The code is:
using System.Collections;
using System.Net;
using MiscUtil.IO;
namespace Soft_inc
{
class MyProject
{
public static string TranslateText(string input, string languagePair)
{
string url = String.Format("http://translate.google.it/?hl=en&ie=UTF8&text={0}&langpair={1}", input, languagePair);
WebClient webClient = new WebClient();
webClient.Encoding = System.Text.Encoding.UTF8;
string result = webClient.DownloadString(url);
result = result.Substring(result.IndexOf("<span title=\"") + "<span title=\"".Length);
result = result.Substring(result.IndexOf(">") + 1);
result = result.Substring(0, result.IndexOf("</span>"));
return result.Trim();
}
public static void Main()
{
string path_file = #"H:\Games\Software.In.v11.7.62\Software.In.v11.7.62\Localization\Italiano\idk\UI.tyd";
string Ftext = System.IO.File.ReadAllText(path_file);
ArrayList ar = new ArrayList();
Console.WriteLine("This may require some time.");
foreach (string line in new LineReader(() => new StringReader(Ftext)))
{
if(line.IndexOf("\"") == -1) continue;
string text = line.Substring(line.IndexOf("\""));
text = text.Replace("\"","");
if(text.Length == 0) continue;
ar.Add(text);
}
int idk = 0;
while(true)
{
idk++;
if(idk == ar.Count) break;
string oldT = (string)ar[idk];
Ftext = Ftext.Replace(oldT, TranslateText(oldT,"en|it"));
}
System.IO.File.WriteAllText("UI.tyd",Ftext);
}
}
}
Maybe it is because the file has 2535 lines of text?
How I can fix this?
You need to use StreamReader class. It is not necessary to read all file content into RAM. Open one StreamReader and one StreamWriter. Reed file line by line and write translated data into a temporary file. When all content is translated just move temp file to needed destination. Don't forget to close source and destination handles before moving.

get a part of string from multiline/column string

Application .net C#
I have problem how to get out (on button click) this (rounded red) value from lista.txt file. In a fact, that's a exchange rate list. Values are changing daily.
Mine is always on the same position.
So far, using line.substring I've got the whole column inline:
5,2599355,3058300,2770031,0057322,4095196,1123050,8419020,7941597,0027418,7470806,9262237,4796281,729514
How do I get just a bold part. Its near end of string (7,479628).
Thanks a lot.
String.Split() should be able to do what you want.
if you already have the column it would be:
var array = column.Split('\t'); //assuming the separator is a tab
In the image it looks like the lines are tab seperated?
You could read each line then perform a split using the tab character....
string[] arsplit = line.Split('\t');
and then grab the item from the array based on index which I presume you'll know
Try something like this
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
namespace ConsoleApplication1
{
class Program
{
const string FILENAME = #"lista.txt";
static void Main(string[] args)
{
StreamReader reader = new StreamReader(FILENAME);
int lineCount = 0;
string inputline = "";
do while((inputline = reader.ReadLine()) != null)
{
if(++lineCount == 13)
{
string[] inputArray = inputline.Trim().Split(new char[] {' ','\t'},StringSplitOptions.RemoveEmptyEntries);
Console.WriteLine("Exchange Rate : '{0}'", inputArray[2]);
break;
}
}
}
}
}
I just received solution that works fine from one guy. His suggestion was to check for EUR which I'm interested for. So, after downloading file, approach is:
int counter = 0;
string line;
System.IO.StreamReader file = new System.IO.StreamReader(fullPath);
while ((line = file.ReadLine()) != null)
{
if (counter == 0)//jump first row, it's header don't need it
{
counter++;
continue;
}
if (line.Contains("EUR"))
{
line = line.Replace(" ", "");//clean spaces
line = line.Substring(3 + 3 + 3 + 8, 8);
Response.Write(line);
}
counter++;
}
file.Close();
So it maybe it can be useful for someone. In this moment I don't know which of your solutions is best. Just want to thank to all of you for help me in so short time.

Creating a list of no duplicate string entries in a text file at C#

I'm a beginner at C# programming.
I wanted to create a text file to the desktop in C# Console, which is wanted to add my input new string value to the created text file's new line.
This is my work:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
namespace noteonce
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("New Word: ");
string newWord = Console.ReadLine();
string wlist = Environment.GetFolderPath(Environment.SpecialFolder.Desktop) + #"\list.txt";
TextWriter inject = new StreamWriter(wlist, true);
inject.WriteLine(newWord);
inject.Close();
Console.WriteLine("New word has been added! ");Console.ReadKey();
}
}
}
I created the file through the console, but I want each of my entered string to be unique, I did some look up on google but I'm so confused. I want the console to tell me that whether the new input already exists or not, If it is, to warn me as "It already exists! Input another word : ", If it does not exist, just to add it to the list. I need your assistance.
Thank you all for your attention. By the help of Mr.Ankitkumar Bhatt, This is my recent work :
static void Main(string[] args)
{
string wlist = Environment.GetFolderPath(Environment.SpecialFolder.Desktop)+#"\list.txt";
FileStream create = File.Open(wlist, FileMode.Create);
create.Close();
for (int i = 0; i < 100; i++)
{
Console.WriteLine("New Word"+#" ("+(100-i)+") :");
string newWord = Console.ReadLine();
string FileContents = File.ReadAllText(Environment.GetFolderPath(Environment.SpecialFolder.Desktop) + #"\list.txt");
TextWriter inject = new StreamWriter(Environment.GetFolderPath(Environment.SpecialFolder.Desktop) + #"\list.txt", true);
if (!FileContents.Contains(newWord))
{
inject.WriteLine(newWord);
inject.Close();
}
else
{
Console.WriteLine("It already exists!");
Console.ReadKey();
inject.Close();
}
}
}
But I want to point that, I want the program to recognize all of items in the list, by my last method, it quite works, but when I close, and open the program again, It doesn't give me the warning that New Word is already exist, doesn't add it to the file neither. How can I do the rest ?
In case of "no duplicate" please, have a look at HashSet<String>; you may find TextWriter and TextReader being too complex - try File.ReadLines(), File.AppendAllLines instead:
static void Main(string[] args) {
// better practice is paths combining
string path = Path.Combine(Environment.SpecialFolder.Desktop, "list.txt");
// unique (no duplicates) strings so far
HashSet<String> hash = new HashSet<string>(
File.ReadLines(path), // file to read from
StringComparer.OrdinalIgnoreCase); // let's ignore words' case ("World", "world")
Console.WriteLine("New Word: ");
string newWord = Console.ReadLine().Trim(); // let's trim spaces: "world " -> "world"
if (!string.IsNullOrEmpty(newWord)) // let's not add an empty string
if (!hash.Contains(newWord)) {
// add new word to the end of file
File.AppendAllLines(path, new string[] {newWord});
Console.WriteLine("New word has been added!");
}
else
Console.WriteLine("It already exists! Input another word");
else
Console.WriteLine("We don't add empty lines.");
Console.ReadKey();
}
In case you want to add several words, one after one (put an empty line to exit):
static void Main(string[] args) {
// better practice is paths combining
string path = Path.Combine(Environment.SpecialFolder.Desktop, "list.txt");
// unique (no duplicates) strings so far
HashSet<String> hash = new HashSet<string>(
File.ReadLines(path), // file to read from
StringComparer.OrdinalIgnoreCase); // let's ignore words' case ("World", "world")
while (true) {
Console.WriteLine("New Word: ");
string newWord = Console.ReadLine().Trim(); // let's trim spaces: "world " -> "world"
if (string.IsNullOrEmpty(newWord))
break;
if (hash.Add(newWord)) {
File.AppendAllLines(path, new string[] {newWord});
Console.WriteLine("New word has been added!");
}
else
Console.WriteLine("It already exists! Input another word.");
}
Console.ReadKey();
}
before injecting word check the word exists or not like below
string FileContents = File.ReadAllText(Environment.GetFolderPath(Environment.SpecialFolder.Desktop) + #"\list.txt");
if (!FileContents.Contains(newWord))
{
// Add to file //
}
this can be accomplished in multiple ways. I will present a solution that most closely will work with your code. There is definitely a more elegant way to accomplish this, but this is a quick and dirty way to accomplish that.
one way is to have a foreach check from your text file so:
var isWordPresent = false;
var textLines = File.ReadAllLines(wlist);
foreach (var line in textLines) {
if (line.contains(newWord) {
isWordPresent = true;
}
}
if (isWordPresent == false) {
inject.WriteLine(newWord);
inject.Close();
isWordPresent = false; //added this portion incase you run this code in a while loop
//so you can reuse it. You would need to have the boolean reset to false
}
1) Read the file and write its content to a string[] (Array of string):
var lines = File.ReadAllLines(wlist , Encoding.UTF8);
2) Read your input and check for duplicates:
var input = Console.ReadLine();
if (lines.Contains(input)) {
//Warning message
} else {
//Success message
}

Searching for a Specific Word in a Text File and Displaying the line its on

I am having trouble attempting to find words in a text file in C#.
I want to find the word that is input into the console then display the entire line that the word was found on in the console.
In my text file I have:
Stephen Haren,December,9,4055551235
Laura Clausing,January,23,4054447788
William Connor,December,13,123456789
Kara Marie,October,23,1593574862
Audrey Carrit,January,16,1684527548
Sebastian Baker,October,23,9184569876
So if I input "December" I want it to display "Stephen Haren,December,9,4055551235" and "William Connor,December,13,123456789" .
I thought about using substrings but I figured there had to be a simpler way.
My Code After Given Answer:
using System;
using System.IO;
class ReadFriendRecords
{
public static void Main()
{
//the path of the file
FileStream inFile = new FileStream(#"H:\C#\Chapter.14\FriendInfo.txt", FileMode.Open, FileAccess.Read);
StreamReader reader = new StreamReader(inFile);
string record;
string input;
Console.Write("Enter Friend's Birth Month >> ");
input = Console.ReadLine();
try
{
//the program reads the record and displays it on the screen
record = reader.ReadLine();
while (record != null)
{
if (record.Contains(input))
{
Console.WriteLine(record);
}
record = reader.ReadLine();
}
}
finally
{
//after the record is done being read, the progam closes
reader.Close();
inFile.Close();
}
Console.ReadLine();
}
}
Iterate through all the lines (StreamReader, File.ReadAllLines, etc.) and check if
line.Contains("December") (replace "December" with the user input).
Edit:
I would go with the StreamReader in case you have large files. And use the IndexOf-Example from #Matias Cicero instead of contains for case insensitive.
Console.Write("Keyword: ");
var keyword = Console.ReadLine() ?? "";
using (var sr = new StreamReader("")) {
while (!sr.EndOfStream) {
var line = sr.ReadLine();
if (String.IsNullOrEmpty(line)) continue;
if (line.IndexOf(keyword, StringComparison.CurrentCultureIgnoreCase) >= 0) {
Console.WriteLine(line);
}
}
}
As mantioned by #Rinecamo, try this code:
string toSearch = Console.ReadLine().Trim();
In this codeline, you'll be able to read user input and store it in a line, then iterate for each line:
foreach (string line in System.IO.File.ReadAllLines(FILEPATH))
{
if(line.Contains(toSearch))
Console.WriteLine(line);
}
Replace FILEPATH with the absolute or relative path, e.g. ".\file2Read.txt".
How about something like this:
//We read all the lines from the file
IEnumerable<string> lines = File.ReadAllLines("your_file.txt");
//We read the input from the user
Console.Write("Enter the word to search: ");
string input = Console.ReadLine().Trim();
//We identify the matches. If the input is empty, then we return no matches at all
IEnumerable<string> matches = !String.IsNullOrEmpty(input)
? lines.Where(line => line.IndexOf(input, StringComparison.OrdinalIgnoreCase) >= 0)
: Enumerable.Empty<string>();
//If there are matches, we output them. If there are not, we show an informative message
Console.WriteLine(matches.Any()
? String.Format("Matches:\n> {0}", String.Join("\n> ", matches))
: "There were no matches");
This approach is simple and easy to read, it uses LINQ and String.IndexOf instead of String.Contains so we can do a case insensitive search.
For finding text in a file you can use this algorithim use this code in
static void Main(string[] args)
{
}
try this one
StreamReader oReader;
if (File.Exists(#"C:\TextFile.txt"))
{
Console.WriteLine("Enter a word to search");
string cSearforSomething = Console.ReadLine().Trim();
oReader = new StreamReader(#"C:\TextFile.txt");
string cColl = oReader.ReadToEnd();
string cCriteria = #"\b"+cSearforSomething+#"\b";
System.Text.RegularExpressions.Regex oRegex = new
System.Text.RegularExpressions.Regex(cCriteria,RegexOptions.IgnoreCase);
int count = oRegex.Matches(cColl).Count;
Console.WriteLine(count.ToString());
}
Console.ReadLine();

The old switcheroo (switch position in file)

I would really appreciate if somebody could help me/offer advice on this.
I have a file, probably about 50000 lines long, these files are generated on a weekly basis. each line is identical in terms of type of content.
original file:
address^name^notes
but i need to perform a switch. i need to be able to switch (on each and every line) the address with the name. so after the switch has been done, the names will be first, and then addresses and then notes, like so:
result file:
name^address^notes
50,000 isn't that much these days, so simply reading in the whole file and outputting the wanted format should work fine for you:
string[] lines = File.ReadAllLines(fileName);
string newLine = string.Empty;
foreach (string line in lines)
{
string[] items = line.Split(myItemDelimiter);
newLine = string.Format("{0},{1},{2}", items[1], items[0], items[2]);
// Append to new file here...
}
How about this?
StreamWriter sw = new StreamWriter("c:\\output.txt");
StreamReader sr = new StreamReader("c:\\input.txt");
string inputLine = "";
while ((inputLine = sr.ReadLine()) != null)
{
String[] values = null;
values = inputLine.Split('^');
sw.WriteLine("{0}^{1}^{2}", values[1], values[0], values[2]);
}
sr.Close();
sw.Close();
Go go gadget REGEX!
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication1
{
class Program
{
static string Switcheroo(string input)
{
return System.Text.RegularExpressions.Regex.Replace
(input,
#"^([^^]+)\^([^^]+)\^(.+)$",
"$2^$1^$3",
System.Text.RegularExpressions.RegexOptions.Multiline);
}
static void Main(string[] args)
{
string input = "address 1^name 1^notes1\n" +
"another address^another name^more notes\n" +
"last address^last name^last set of notes";
string output = Switcheroo(input);
Console.WriteLine(output);
Console.ReadKey(true);
}
}
}

Categories

Resources