C# Text file question (help)

cyberbrute

Registered Member
Joined
Jul 29, 2013
Messages
72
Reaction score
50
I am working with .txt files in C#, I want a functionality that if any text already exist in my .txt file, it should not write it.

Can somebody Please help me?

Thank you
 
Code:
var filename = @"c:\test.txt";
var textToWrite = "your text here";
string fileContents;


// Get File Text
using (var sr = new StreamReader(filename))
{
    fileContents = sr.ReadToEnd();
}


// Write to File
using (var sw = new StreamWriter(filename, true))
{
    // check if text already exists in file
    if (!fileContents.Contains(textToWrite))
    {
        sw.WriteLine(textToWrite); // or use sw.Write depending on the usage scenario
    }
}
 
Code:
var contents = File.ReadAllText(@"c:\path\file.txt");
if(!contents.Contains(strToFind)){
    File.WriteAllText(@"c:\path\file.txt", contentsToWrite);
}
 
string textLineToTest = "xyz";

FileStream stream = File.OpenRead("textfile");
if (stream.Length > 0)
{
// file is not empty
return;
}

using (TextReader tr = new StreamReader(stream))
{
string line;
while ((line = tr.ReadLine()) != null)
{
if (line.IndexOf(textLineToTest, StringComparison.Ordinal) != -1)
{
//you got the text
}
}
}
 
Last edited:
Back
Top