将打开的文本文件保存到原始位置

时间:2017-06-28 17:39:16

标签: c# datagridview openfiledialog savefiledialog

我正在创建一个应用程序,允许我打开一个.txt文件并在DataGridView中编辑值(weight = 60,height = 50等)。我的问题是我能够使用OpenFileDialog上传.txt文件,但无法将其写入并将其保存在以前的位置。

为了澄清,这是我上传文本文件的方法:

private void btnUpload_Click(object sender, EventArgs e)
    {
        Stream myStream;
        openFileDialog1.FileName = string.Empty;
        openFileDialog1.InitialDirectory = "C:\\";
        if (openFileDialog1.ShowDialog() == DialogResult.OK)
        {
            var compareType = StringComparison.InvariantCultureIgnoreCase;
            var fileName = Path.GetFileNameWithoutExtension(openFileDialog1.FileName);
            var extension = Path.GetExtension(openFileDialog1.FileName);
            if (extension.Equals(".txt", compareType))
            {
                try
                {
                    using (myStream = openFileDialog1.OpenFile())
                    {              
                        string file = Path.GetFileName(openFileDialog1.FileName);
                        string path = Path.GetDirectoryName(openFileDialog1.FileName);
                        StreamReader reader = new StreamReader(openFileDialog1.FileName);
                        string line;

                        while ((line = reader.ReadLine()) != null)
                        {
                            string[] words = line.Split('=');
                            paramList.Add(new Parameter(words[0], words[1]));
                        }
                        BindGrid();
                    }
                }

我试图保存文件:

public void WriteToTextFile(DataGridView dgvParam)
    {
        String file_name = Path.GetFileNameWithoutExtension(openFileDialog1.FileName);
        using (StreamWriter objWriter = new StreamWriter(openFileDialog1.FileName))
        {
            for (Int32 row = 0; row < dgvParam.Rows.Count - 1; row++)
            {
                StringBuilder sb = new StringBuilder();
                for (Int32 col = 0; col < dgvParam.Rows[row].Cells.Count; col++)
                {
                    if (!String.IsNullOrEmpty(sb.ToString()))
                        sb.Append("=");  //any delimiter you choose
                    sb.Append(dgvParam.Rows[row].Cells[col].Value.ToString().ToUpper());
                }
                objWriter.WriteLine(sb.ToString());
            }
        }

它说openFileDialog目前正在使用,它无法达到它!任何建议或建议都会非常感激!

1 个答案:

答案 0 :(得分:1)

您需要处置reader变量。

你应该完全摆脱第一个using语句并将其包含在using语句中。