简体   繁体   中英

How to add a string to a specific line in a text file using C#

i need your help, i'm trying to add a string "MyString" to a specific line in a text file but couldn't yet. for exmple this is the content of my Text file :

First Name.
Last Name.
Date of Birth.
Counrty.

now what i'm looking for is add "MyString" will be "City" just in the next line after the word "Date of Birth". so the result can be like this :

First Name.
Last Name.
Date of Birth.
City.
Counrty. 

I've tried:

File.AppendAllText(@"C:\\Users\\Volki\\Desktop\\TextFile.txt", 
    string.Format("{0}{1}", "Date of Birth.", "City"));

try Something like this:

string PathFile=@"c:\temp\testxx.TXT";

List<string> Listvalue = File.ReadAllLines(PathFile).ToList();
int IndexSearch = Listvalue.IndexOf("Date of Birth.");

if (IndexSearch>=0)
{
   Listvalue.Insert(IndexSearch+1, "City."); 
   File.WriteAllLines(PathFile, Listvalue.ToArray()); 
}
  • Create string[] currFile and read from your file into it (you will get array with 4 elements in it)
  • Create another string[] newFile but with size of currFile.Length + 1
  • Copy currFile to newFile but forth line set to fifth (into new file you have first 3 lines, one empty and fifth line.
  • Store city into newFile 's forth line
  • Save that to text file

If i made some mistake post in comment, i set this up in hurry

EDIT:

What you probably do is use Newtonsoft.Json so you have class:

public User
{
    public string FirstName;
    public string LastName;
    public DateTime dateOfBirth;
    public string Country;
}

And then you use it like this:

public MyClass
{    

    public MyClass()
    {
        User user = new User();
        user.FirstName = "User1";
        ...
        WriteUser(user);

        User user1 = ReadUser();
        string username = user1.FirstName;
    }

    void WriteUser(User user)
    {
        string stringToWriteToFile = JsonConvert.SerializeObject(user);
        //Write this string to file
    }

    User ReadUser()
    {
        string stringFromFile = ...
        return JsonConvert.DeserializeObject<User>(stringFromFile);
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM