且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何使用C#从文本文件中删除一行

更新时间:2021-07-20 00:08:03

循环在所有行上创建原始行的副本,在此处放弃匹配的行。在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.