Tarheel81
Tarheel81

Reputation: 13

Save Opened Text File to Original Location

I am creating an application that will allow me to open a .txt file and edit the values (weight=60, height =50, etc) in a DataGridView. My issue is that I am able to upload the .txt file using OpenFileDialog but am unable to write over and save it in it's previous location.

For clarification, here is my method to upload text files:

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();
                    }
                }

And what I've tried to save the file:

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());
            }
        }

It says it is openFileDialog is currently in use and it cannot reach it! Any suggestions or recommendations would be really appreciated!

Upvotes: 0

Views: 81

Answers (1)

SLaks
SLaks

Reputation: 887413

You need to dispose your reader variable.

You should get rid of the first using statement entirely and wrap that in a using statement instead.

Upvotes: 1

Related Questions