平時少不了字符串操作,以下代碼是爲解決文本去重功能,沒什麼內容,主要是初次接觸控制檯程序,記錄一下
程序入口:
namespace SotringTool
{
class Program
{
private static StringTool m_Tool;
static void Main(string[] args)
{
m_Tool = new StringTool(args);
m_Tool.OpenFile();
}
}
}
當把文件拖到程序上時(.exe),在程序入口傳入的參數就是你拖入文本的路徑,直接打開是參數爲null
using System;
using System.IO;
using System.Linq;
namespace SotringTool
{
public class StringTool
{
public StringTool(string[] args)
{
if ( args!= null && args.Length >= 1)
{
m_path = args[0];
}
}
private string m_path = null;
public void OpenFile()
{
if (string.IsNullOrEmpty(m_path))
{
Console.WriteLine("將文件拖至此處");
m_path = Console.ReadLine();
}
if (File.Exists(m_path))
{
ReadFile(m_path);
}
else
{
m_path = null;
Console.WriteLine("請放入有效文件");
OpenFile();
}
}
private void ReadFile(string path)
{
try
{
string worlds = File.ReadAllText(path);
char[] char_list = worlds.ToCharArray();
string str = new string(char_list.Distinct().ToArray());
WriteFile(path, str);
Console.WriteLine("請放入有效文件");
}
catch (Exception e)
{
Console.WriteLine("讀取文件失敗");
Console.WriteLine(e.Message);
m_path = null;
OpenFile();
}
}
private void WriteFile(string path, string content)
{
try
{
byte[] data = System.Text.Encoding.UTF8.GetBytes(content);
File.WriteAllBytes(path, data);
Console.WriteLine("輸入0退出程序");
string exit = Console.ReadLine();
if (exit.Equals("0"))
{
Environment.Exit(0);
}
else
{
Console.WriteLine("推出失敗,按任意鍵離開程序");
Console.ReadLine();
}
//
}
catch (Exception e)
{
Console.WriteLine("保存文件失敗");
Console.WriteLine(e.Message);
m_path = null;
OpenFile();
}
}
}
}