当前位置: 代码迷 >> C# >> C# 读取文件中的数据,并保存生成新的解决方案
  详细解决方案

C# 读取文件中的数据,并保存生成新的解决方案

热度:330   发布时间:2016-05-05 02:54:45.0
C# 读取文件中的数据,并保存生成新的
Button1,Button2    Button1用来浏览某个文件,Button2用来生成一个文件。
Button1浏览了一个文件,选中他。  点击一下Button2,在指定路径生成了一个新的文件。
生成的新文件通过split去掉了浏览文件中的所有","号
------解决思路----------------------
看起来像是操作txt文件



        public static void DataSave(string saveDirectory, string saveName, string saveContent)
        {
            string filePath = saveDirectory + saveName + ".txt";
            if (!Directory.Exists(saveDirectory))
            {
                Directory.CreateDirectory(saveDirectory);
            }
            using (StreamWriter sw = File.AppendText(filePath))
            {
                sw.Write(saveContent);
            }
        }





private void button1_Click(object sender, EventArgs e)
{
            OpenFileDialog openFile = new OpenFileDialog();
            if (openFile.ShowDialog() == DialogResult.OK)
            {
                using (StreamReader streamReader = File.OpenText(openFile.FileName))
                {
                    string txtLine = streamReader.ReadToEnd();
                    //存到对应的控件中修改例如textBox1
                }
            }
}

private void button2_Click(object sender, EventArgs e)
{
            string fileDirectory = String.Empty;
            FolderBrowserDialog fbd = new FolderBrowserDialog();
            if (fbd.ShowDialog() == DialogResult.OK)
            {
                fileDirectory = fbd.SelectedPath;
            }

            DataSave( fileDirectory ,"文件名称","文件内容");
}


------解决思路----------------------
string filePath = null;
string newDirectory = @"D:/demo/";
private void btn1_Click(object sender, EventArgs e)
{
    OpenFileDialog op = new OpenFileDialog();
    if (op.ShowDialog() == System.Windows.Forms.DialogResult.OK)
    {
        filePath = op.FileName;
    }
}
private void btn2_Click(object sender, EventArgs e)
{
    if (filePath != null)
    {
        string name = Path.GetFileName(filePath);
        using (StreamReader sr = new StreamReader(this.filePath))
        {
            string txt = sr.ReadToEnd();
            using (var sw = File.CreateText(Path.Combine(newDirectory, name)))
            {
                sw.Write(txt.Replace(",", string.Empty));
            }
        }
    }
}

大致代码就这样了,你看着办吧
  相关解决方案