简体   繁体   English

在WPF中编辑文本文件中的一些文本

[英]Editing some text in a text file in WPF

I am new to using forms and C # and trying to do an assignment to create a phone book. 我不熟悉使用表单和C#,并尝试进行分配以创建电话簿。 I have different options in my phone book 我的电话簿中有不同的选择

  • To Add a contact 添加联系人
  • To show all contacts 显示所有联系人
  • and To edit a certain contact. 和编辑某个联系人。

I am having trouble in how to do editing when text is stored in a text file. 将文本存储在文本文件中时,如何进行编辑时遇到麻烦。 I have the following code for my add which adds name, phone number and email. 我的添加代码如下,其中添加了姓名,电话号码和电子邮件。 How would i be able to edit one of the names from a list of contacts that is saved in the text file? 我如何能够从文本文件中保存的联系人列表中编辑姓名之一?

Add Code: 添加代码:

private void addButton_Click(object sender, RoutedEventArgs e)
{
    TextWriter writer = new StreamWriter("D:\\class1.txt", append: true);
    try
    {
            string Name01 = firstName.Text;
            string Name02 = lastName.Text;
            string Phone1 = mobile.Text; 
            string Phone2 = homePhone.Text;
            string emailadd = email.Text;
            string Informtion = Name01 + "\n" + Name02 + "\n" + Phone1 + "\n" + Phone2 + "\n" + emailadd;
            writer.WriteLine("---------------");
            writer.WriteLine(Informtion);
            MessageBox.Show("Success!! Contact information added for: " +Name01 + " " +Name02);
        }
        catch (Exception ex)
        {
            throw ex;
        }  
        finally
        {
            writer.Close();
            writer.Dispose();
        }
    }

It appears your text file is not structured. 看来您的文本文件不是结构化的。 Unstructured text is very difficult to search and edit programmatically. 非结构化文本很难以编程方式进行搜索和编辑。

Try using XML or JSON formatted text instead which will allow you to work with entries much easier, especially if you use one of the many open source libraries specifically developed to work with entries in these two formats... 尝试改用XML或JSON格式的文本,这将使您更轻松地处理条目,特别是如果您使用专门为处理这两种格式的条目而开发的众多开源库之一...

Let's take this XML for example: 让我们以这个XML为例:

<?xml version="1.0" encoding="UTF-8"?>
<SnomIPPhoneDirectory>
  <Title>PhoneList - Snom</Title>
  <DirectoryEntry>
    <Name>Friend, First</Name>
    <Telephone>555-456-7890</Telephone>
  </DirectoryEntry>
  <DirectoryEntry>
    <Name>Person, Second</Name>
    <Telephone>555-654-0987</Telephone>
  </DirectoryEntry>
  <SoftKeyItem>
    <Name>F1</Name>
    <Label>Dial</Label>
    <SoftKey>F_ENTER</SoftKey>
  </SoftKeyItem>
</SnomIPPhoneDirectory>

Using a library or even XML functionality built into .NET framework it would be trivial to work with phone book entries in the object oriented way where you would not have to do any string parsing. 使用内置于.NET框架中的库甚至XML功能,以面向对象的方式处理电话簿条目将变得很简单,而您无需进行任何字符串解析。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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