1. This site uses cookies. By continuing to use this site, you are agreeing to our use of cookies. Learn More.

C# Text file question (help)

Discussion in 'C, C++, C#' started by cyberbrute, Aug 11, 2013.

  1. cyberbrute

    cyberbrute Registered Member

    Joined:
    Jul 29, 2013
    Messages:
    72
    Likes Received:
    47
    Occupation:
    Student
    Location:
    Pakistan
    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
     
  2. Standard Toaster

    Standard Toaster Regular Member

    Joined:
    Aug 29, 2009
    Messages:
    335
    Likes Received:
    190
    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
        }
    }
    
     
  3. rootjazz

    rootjazz Jr. VIP Jr. VIP

    Joined:
    Dec 21, 2012
    Messages:
    614
    Likes Received:
    313
    Occupation:
    Developer
    Location:
    UK
    Home Page:
    Code:
    var contents = File.ReadAllText(@"c:\path\file.txt");
    if(!contents.Contains(strToFind)){
        File.WriteAllText(@"c:\path\file.txt", contentsToWrite);
    }
    
     
  4. botrockets

    botrockets Regular Member

    Joined:
    Mar 16, 2013
    Messages:
    272
    Likes Received:
    463
    Occupation:
    Software Developer
    Location:
    Saint T.N.
    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: Sep 25, 2013