「C#」 简单文本去重

/*
 * / <summary>
 * / 程序入口
 * / </summary>
 * / <param name="args">参数</param>
 */
public static void Main( string[] args )
{
    try
    {
        string path = @"c:\test.txt";
        ReadInfoFromFile( path );
    }
    catch ( Exception ex )
    {
        Console.WriteLine( ex.ToString() );
    }
}


private static void ReadInfoFromFile( string filePath )
{
    if ( File.Exists( filePath ) )
    {
        List<string> list = new List<string>();
/* 打开文件时 一定要注意编码 也许你的那个文件并不是GBK编码的 */
        using ( StreamReader sr = new StreamReader( filePath, Encoding.GetEncoding( "GBK" ) ) )
        {
            while ( !sr.EndOfStream )               /* 读到结尾退出 */
            {
                string temp = sr.ReadLine();
                if ( !list.Contains( temp ) )   /* 去除重复的行 */
                {
                    list.Add( temp );
                }
            }
        }
/* 写回去,第二个参数 Append = false ,就是说覆盖原来的 */
        using ( StreamWriter sw = new StreamWriter( filePath, false, Encoding.GetEncoding( "GBK" ) ) )
        {
            foreach ( string line in list )
            {
                sw.WriteLine( line );
            }
        }
    }
}

猜你喜欢

转载自blog.csdn.net/iverson1180/article/details/81604409
今日推荐