Hello All :

Is there any idea to create a txt file by C#, I want it to save all the status of controls of the form inside it????

Thanks for support

Dani AI

Generated

Short answer and the important distinction: a desktop app (WinForms/WPF) can create a plain text file anywhere the running user has permission to write; a web app (ASP.NET) cannot silently write to a visitor's local partition (browser security). wanted a "direct" save with no dialog — that works for desktop apps but not for ordinary web pages. Below are practical, safe options that build on 's StreamWriter idea and 's suggestion to use settings.

For a simple desktop (WinForms) approach, write a small key=value file on your Save button and read it back on startup. Use a full path (or a per-user folder) and check permissions:

// Save button (WinForms)
var lines = new List<string> {
  "textBox1=" + textBox1.Text,
  "checkBox1=" + (checkBox1.Checked ? "1" : "0")
};
var path = @"C:\Temp\formstate.txt"; // ensure folder exists and app has rights
File.WriteAllLines(path, lines);
// On Form.Load
if (File.Exists(path)) {
  foreach (var ln in File.ReadAllLines(path)) {
    var kv = ln.Split(new[]{'='}, 2);
    if (kv[0] == "textBox1") textBox1.Text = kv[1];
    if (kv[0] == "checkBox1") checkBox1.Checked = (kv[1] == "1");
  }
}

A more structured, per-user option is application settings (persisted automatically and safer than writing into Program Files). Create user-scoped settings and use:

Properties.Settings.Default.Text1 = textBox1.Text;
Properties.Settings.Default.Checked1 = checkBox1.Checked;
Properties.Settings.Default.Save();

For ASP.NET: you can save control values on the server (for example inside App_Data or a database) and optionally offer a downloadable text file, but you cannot force a silent write to the client machine. Example (server-side):

var file = Server.MapPath("~/App_Data/formstate.txt");
File.WriteAllText(file, content);
Response.ContentType = "text/plain";
Response.AddHeader("Content-Disposition","attachment; filename=formstate.txt");
Response.Write(content);

Cautions: always sanitize and validate values, prefer per-user folders (Environment.GetFolderPath) or App_Data rather than arbitrary paths, and ensure proper file-system permissions. If a truly silent client-side save is required, use a desktop helper app — browsers will not allow that for security reasons.

Recommended Answers

All 6 Replies

Here is a simple general way to write to a text file:

// FileWrite - write input from the Console into a text file

using System;
using System.IO;

namespace FileWrite
{
  public class Class1
  {
    public static void Main(string[] args)
    {
      // create the filename object - the while loop allows
      // us to keep trying with different filenames until
      // we succeed
      StreamWriter sw = null;
      string sFileName = "";
      while(true)
      {
        try
        {
          // enter output filename (simply hit Enter to quit)
          Console.Write("Enter filename "
                      + "(Enter blank filename to quit):");
          sFileName = Console.ReadLine();
          if (sFileName.Length == 0)
          {
            // no filename - this jumps beyond the while
            // loop to safety
            break;
          }

          // open file for writing; throw an exception if the
          // file already exists:
          //   FileMode.CreateNew to create a file if it
          //                   doesn't already exist or throw
          //                   an exception if file exists
          //   FileMode.Append to create a new file or append
          //                   to an existing file
          //   FileMode.Create to create a new file or 
          //                   truncate an existing file

          //   FileAccess possibilities are:
          //                   FileAccess.Read, 
          //                   FileAccess.Write,
          //                   FileAccess.ReadWrite
          FileStream fs = File.Open(sFileName, 
                                    FileMode.CreateNew, 
                                    FileAccess.Write);

          // generate a file stream with UTF8 characters
          sw = new StreamWriter(fs, System.Text.Encoding.UTF8);

          // read one string at a time, outputting each to the
          // FileStream open for writing
          Console.WriteLine("Enter text; enter blank line to stop");
          while(true)
          {
            // read next line from Console;
            // quit if line file is blank
            string sInput = Console.ReadLine();
            if (sInput.Length == 0)
            {
              break;
            }

            // write the line just read to output file
            sw.WriteLine(sInput);
          }

          // close the file we just created
          sw.Close();
          sw = null;
        }
        catch(IOException fe)
        {
          // whoops -- an error occurred somewhere during
          // the processing of the file - tell the user 
          // what the full name of the file is:
          // take the path name onto the filename
          string sDir = Directory.GetCurrentDirectory();
          string s = Path.Combine(sDir, sFileName);
          Console.WriteLine("Error on file {0}", s);

          // now output the error message in the exception
          Console.WriteLine(fe.Message);
        }
      }

      // wait for user to acknowledge the results
      Console.WriteLine("Press Enter to terminate...");
      Console.Read();
    }
  }
}

Thank you very much ,,,, but I was wonder if I have a form inside it checkbox textbox ...etc while I want to press my save button I want a directly text file created in any partition (without save dialog) saving the status of those controls ....so can I do it in C#??????

thanks for support....

Extract the generated code by VS IDE, save it to the text file.

but, if you need to save some properties of the controls, I recommend to use .settings file

Hello :

Thanks a lot , but how can I create s setting file can you explain please ???

Project->add new item->Settings file

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.