如何使用C#从文本文件中删除一行 [英] How to remove a line from Text File using C#

查看:138
本文介绍了如何使用C#从文本文件中删除一行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的应用程序可以将用户添加到文本文件中,当我单击添加用户按钮时,会在我的文本文件中附加一行。但是,如果我想删除用户?这可以通过在textBox中编写用户名并单击删除用户按钮来完成,但我不知道用什么来删除textFile中的行。



例如,我存储用户名的textFile有:

My app is able to add "users" to a text file, when I click on "Add User" button, a line is appended to my text file. But if I want to remove an user? That would be accomplished by writing the username in a textBox and click on "Remove User" button, but I don't know what to use to remove the line from the textFile.

For example, my textFile that is storing usernames has:

User01<br />
User02<br />
ChrisCreateBoss<br />
ChrisHD22<br />





如果我想删除 ChrisHD22 ,我必须在我的textBox1中编写ChrisHD22,当单击删除按钮时,streamWriter将删除显示 ChrisHD22 的行并让其他行保持不变。 />


我目前正在使用它来检查文本文件中是否存在用户名:



And if I want to remove ChrisHD22, I have to write ChrisHD22 in my textBox1 and when Remove button is clicked, a streamWriter would remove the line that says ChrisHD22 and let the other lines untouched.

I'm currently using this to check if the username exists in the text file:

if(File.ReadLines(usersPath).Contains(usertxt2.Text))
           {
              // What can I write here?
           }





如果我不清楚请告诉我。

先谢谢 - CCB



If I wasn't clear please let me know.
Thanks in Advance - CCB

推荐答案

循环在所有行上创建原始行的副本,在此处放弃匹配的行。在LINQ中有这样的东西(或者你也可以用一些嵌套的if来实现它作为foreach循环):
Loop over all lines and create a copy of the original lines where you leave away the matching lines. Something like this in LINQ (or you may implement it as foreach loop too with some nested if):
string item = usertxt2.Text.Trim();
var lines = File.ReadAllLines(usersPath).Where(line => line.Trim() != item).ToArray();
File.WriteAllLines(usersPath, lines);



干杯

Andi


Cheers
Andi


使用System.Runtime.Serialization中的'DataContract和'DataMember属性,您可以轻松地序列化和反序列化类。这里显示的代码尽可能简单,以说明所涉及的技术。



开头:



1. Windows窗体项目:



a。一个TextBox,'textBox1

b。 ListBox,'listBox1

c。 4个按钮:'btnAdd,'btnDelete,'btnSave,'btnLoad



2.这个简单的类:
Using the 'DataContract and 'DataMember Attributes in System.Runtime.Serialization you can easily serialize and de-serialize a Class. The code shown here is as simple as possible, to illustrate the techniques involved.

Start with:

1. A Windows Forms Project with:

a. a TextBox, 'textBox1
b. ListBox, 'listBox1
c. 4 buttons: 'btnAdd, 'btnDelete, 'btnSave, 'btnLoad

2. This simple class:
using System;
using System.Collections.Generic;
using System.IO;
using System.Runtime.Serialization;
using System.Windows.Forms;

namespace March8_SimpleDB
{
    [DataContract]
    public class Users
    {
        [DataMember]
        public List<string> UserList { set; get; }
        
        [DataMember]
        public string FileLocation { set; get; }

        private static DataContractSerializer theSerializer;

        public Users()
        {
            UserList = new List<string>();

            // default write location
            FileLocation = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);
            FileLocation = Path.Combine(FileLocation, @"DefaultUsersFile.xml");
        }

        public void Add(string newUser)
        {
            UserList.Add(newUser);
        }

        public void Remove(string xUser)
        {
            UserList.Remove(xUser);
        }

        public bool Contains(string user)
        {
            return (UserList.Contains(user));
        }

        public static void Serialize(Users theUsers)
        {
            if(theSerializer == null) theSerializer = new DataContractSerializer(typeof(Users));

            try
            {
                using (FileStream stream = new FileStream(theUsers.FileLocation, FileMode.Create))
                {
                    theSerializer.WriteObject(stream, theUsers);
                }
            }
            catch (Exception)
            {
                throw new InvalidDataContractException("Can't save file to: " + theUsers.FileLocation);
            }

            MessageBox.Show("file successfully saved");
        }

        public static Users DeSerialize(Users theUsers)
        {
            // lazy load
            if (theSerializer == null) theSerializer = new DataContractSerializer(typeof(Users));

            Users result = null;

            using (FileStream stream = new FileStream(theUsers.FileLocation, FileMode.Open))
            {
                try
                {
                    result = (Users) theSerializer.ReadObject(stream);
                    theUsers.UserList = result.UserList;
                }
                catch (Exception)
                {
                    throw new InvalidDataContractException("Can't read file at: " + theUsers.FileLocation);
                }          
            }

            MessageBox.Show("file read successfully");

            return result;
        } 
    }
}</string></string>

以下是在主窗体中序列化和反序列化此类的方法:

Here's how you would serialize and de-serialize this class in the "main Form:"

using System;
using System.Windows.Forms;

namespace March8_SimpleDB
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private Users TheUsers;

        private void Form1_Load(object sender, EventArgs e)
        {
            TheUsers = new Users();
        }

        private void btnAdd_Click(object sender, EventArgs e)
        {
            string text = textBox1.Text;

            // no valid entry ?
            if (string.IsNullOrWhiteSpace(text)) return;

            // already have this User name ?
            if (TheUsers.Contains(text)) return;

            TheUsers.Add(text);

            listBox1.Items.Add(text);
        }

        private void btnDelete_Click(object sender, EventArgs e)
        {
            object selection = listBox1.SelectedItem;

            // no selection ?
            if (selection == null) return;

            string text = selection.ToString();

            TheUsers.Remove(text);
            listBox1.Items.Remove(selection);
        }

        private void btnSave_Click(object sender, EventArgs e)
        {
            TheUsers.UserList.Clear();

            foreach (var itm in listBox1.Items)
            {
                TheUsers.Add(itm.ToString());
            }

            Users.Serialize(TheUsers);
        }

        private void btnLoad_Click(object sender, EventArgs e)
        {
            Users.DeSerialize(TheUsers);

            listBox1.Items.Clear();

            foreach (string user in TheUsers.UserList)
            {
                listBox1.Items.Add(user);
            }
        }
    }
}

注意:



1.是的,你可以使用'DataContract /'DataMember来序列化继承自通用列表或字典的类,但为了做到这一点,需要解决方法,因为序列化程序将只编写字典中的LIst或KeyValue对中的Items ,并将忽略标有DataMember的任何其他字段/属性。



2.静态类成员将被Serilializer忽略。



3.您可以使用'DataContract序列化字段;我认为,由于许多原因,更好的做法是养成使用Properties而不是Fields的习惯。请记住,即将推出的C#6.0将允许轻松实现属性的内联初始化。



评论,建议,欢迎。

Notes:

1. Yes, you can use 'DataContract/'DataMember to serialize a Class that inherits from a Generic List, or Dictionary, but in order to do that a work-around is required because the Serializer will write only the Items in the LIst or KeyValue Pairs in the Dictionary, and will ignore any other Fields/Properties marked with 'DataMember.

2. Static Class members will be ignored by the Serilializer.

3. You can serialize Fields with 'DataContract; I think it's better practice, for many reasons, to get in the habit of using Properties rather than Fields. Keep in mind that the upcoming C# 6.0 will allow easy in-line initialization of Properties.

Comments, suggestions, welcome.


这篇关于如何使用C#从文本文件中删除一行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆