Hi, I knew before, the coding to write from a textbox to a textfile and read from one and similar thigns to it. But I lost all my projects and i forgot how to do it.

What I'm trying to do is a have the information the user inputs into a textbox have it saved into a text file. I thoguth I was getting the process right but I kept getting this error:

"The process cannot access the file 'C:\Users\MomDad\Desktop\username.txt' because it is being used by another process."

I was using this code below. Also, I'm tryign to have it to that when the user checks the checkbox, it will save the information he entered into the textfile which will be created:

if (File.Exists(d + @"\username.txt") == false)
                        {
                             File.Create(d + @"\username.txT");
                             string un = d + @"\username.txt";
                             using (StreamWriter sw1 = new StreamWriter(un))
                             {
                                     sw1.Write(textBox1.Text);
                                     sw1.Close();
                             }
                        }
                        else
                        {
                            File.Delete(d + @"\username.txt");
                            File.Create(d + @"\username.txT");
                            string un = d + @"\username.txt";
                            using (StreamWriter sw1 = new StreamWriter(un))
                            {
                                  sw1.Write(textBox1.Text);
                                  sw1.Close();

d by the way, just stands for the desktop directory string. string d = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);

The code of line highlights where I start 'using' with the error I described above. I think I'm missing something but I don't know what it is.

Thanks for the help in advance!

Recommended Answers

All 5 Replies

File.Create() returns an open file stream to the file. So in this case your call to File.Create creates the file and opens it then you're attempting to open it with a second filestream which results in the error. The filestream overload can create the file for you -- so it is not necessary to manually create the file.

Example:

private static void WriteTextFile()
    {
      const string fileName = @"C:\file.txt";
      using (FileStream fs = new FileStream(fileName, FileMode.OpenOrCreate))
      {
        using (StreamWriter sw = new StreamWriter(fs))
        {
          sw.Write("text here...");
        }
      }
    }

ooh, thank you. I will try it immediately.

Does the same thign apply with stream reader.

This had nothing to do with StreamReader or StreamWriter , it had to do with File.Create() .

Please mark this thread as solved if you have found an answer to your question and good luck!

Well then "How Can I Write & Read From Tex Files / TextBoxes"

I'm pretty sure that was my official question...

For a single text box:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;

namespace daniweb.rwtextboxes
{
  public partial class frmSingleTextBox : Form
  {
    private const string fileName = @"C:\txtBoxRW.txt";

    public frmSingleTextBox()
    {
      InitializeComponent();
    }

    private void buttonSave_Click(object sender, EventArgs e)
    {
      File.WriteAllText(fileName, textBox1.Text);
    }

    private void buttonLoad_Click(object sender, EventArgs e)
    {
      textBox1.Text = File.ReadAllText(fileName);
    }
  }
}

For multiple text boxes:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Xml.Serialization;
using System.Xml;

namespace daniweb.rwtextboxes
{
  public partial class frmMultiTextBoxes : Form
  {
    private const string fileName = @"C:\txtBoxRW_Multi.txt";

    public frmMultiTextBoxes()
    {
      InitializeComponent();
    }

    private void buttonSave_Click(object sender, EventArgs e)
    {
      TextBox[] boxes = GetTextBoxes();
      List<SerializedTextBoxInfo> lst = new List<SerializedTextBoxInfo>();
      foreach (TextBox tb in boxes)
      {
        lst.Add(new SerializedTextBoxInfo(tb.Name, tb.Text));
      }
      XmlSerializer ser = new XmlSerializer(typeof(List<SerializedTextBoxInfo>));
      using (FileStream fs = new FileStream(fileName, FileMode.Create))
      {
        ser.Serialize(fs, lst);
        fs.Flush();
        fs.Close();
      }
    }

    private void buttonLoad_Click(object sender, EventArgs e)
    {
      XmlSerializer ser = new XmlSerializer(typeof(List<SerializedTextBoxInfo>));
      List<SerializedTextBoxInfo> lst;
      using (FileStream fs = new FileStream(fileName, FileMode.Open))
      {
        lst = (List<SerializedTextBoxInfo>)ser.Deserialize(fs);
      }
      foreach (SerializedTextBoxInfo info in lst)
      {
        Control[] ctrls = this.Controls.Find(info.Name, true);
        if ((ctrls != null) && (ctrls.Length > 0) && ((ctrls[0] as TextBox) != null))
        {
          ((TextBox)ctrls[0]).Text = info.Text;
        }
      }
    }

    private TextBox[] GetTextBoxes()
    {
      List<TextBox> result = new List<TextBox>();
      foreach (Control c in this.Controls)
      {
        result.AddRange(GetTextBoxes(c));
      }
      return result.ToArray();
    }
    private static TextBox[] GetTextBoxes(Control c)
    {
      List<TextBox> result = new List<TextBox>();
      TextBox tb = (c as TextBox);

      if (tb != null)
        result.Add(tb);

      foreach (Control child in c.Controls)
      {
        tb = (child as TextBox);
        if (tb != null)
          result.Add(tb);
        result.AddRange(GetTextBoxes(child));
      }
      return result.ToArray();
    }
  }
  public class SerializedTextBoxInfo
  {
    public string Name { get; set; }
    public string Text { get; set; }
    public SerializedTextBoxInfo()
    {
    }
    public SerializedTextBoxInfo(string Name, string Text)
      : this()
    {
      this.Name = Name;
      this.Text = Text;
    }
  }
}
commented: Your aid stands beyond contest. +4
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.