How can I save data/information to text file and read back ?

rhodanny 166 Reputation points
2021-12-21T05:01:02.123+00:00
private void SaveData(string contentToSave, string fileName)
        {
            string applicationPath = Path.GetFullPath(System.AppDomain.CurrentDomain.BaseDirectory); // the directory that your program is installed in
            string saveFilePath = Path.Combine(applicationPath, fileName);
            StreamWriter w = new StreamWriter(saveFilePath, true);
            w.WriteLine(contentToSave);
            w.Close();
        }

For example in this part of the code :

lblLastDownloaded.Text = DateTime.Now.ToString();

but I want to keep this DateTime.Now so when the user close the application and open it again it will load the last DateTime.Now
so when I'm doing this line assigning the DateTime.Now to the label text I want also to save it and load it to the label text when running the application again.

and same for other stuff like saving information like this and or small data like keep trackBar1 current value for example.

Windows Forms
Windows Forms
A set of .NET Framework managed libraries for developing graphical user interfaces.
1,834 questions
C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
10,276 questions
0 comments No comments
{count} votes

3 answers

Sort by: Most helpful
  1. Jack J Jun 24,296 Reputation points Microsoft Vendor
    2021-12-21T07:47:13.13+00:00

    @rhodanny , you can try to use FormClosing event to write data to file and read the last line of the file if you want to access the last DateTime.Now.

    Here is a code example you could refer to.

    private void Form1_Load(object sender, EventArgs e)  
            {  
                string applicationPath = Path.GetFullPath(System.AppDomain.CurrentDomain.BaseDirectory); // the directory that your program is installed in  
                string saveFilePath = Path.Combine(applicationPath, "1.txt");  
                if(File.Exists(saveFilePath))  
                {  
                    string text = File.ReadAllLines(saveFilePath).LastOrDefault();  
                    label1.Text=text;  
                }  
                else  
                {  
                    label1.Text="the first time you come in ";  
                }  
                 
                
            }  
      
            private void Form1_FormClosing(object sender, FormClosingEventArgs e)  
            {  
                string applicationPath = Path.GetFullPath(System.AppDomain.CurrentDomain.BaseDirectory); // the directory that your program is installed in  
                string saveFilePath = Path.Combine(applicationPath, "1.txt");  
                StreamWriter w = new StreamWriter(saveFilePath, true);  
                w.WriteLine(DateTime.Now.ToString());  
                w.Close();  
            }  
      
            private void button1_Click(object sender, EventArgs e)  
            {  
                string str = DateTime.Now.ToString();  
                MessageBox.Show(str);  
            }  
    

    Result:

    159219-image.png


    If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".
    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    0 comments No comments

  2. Jaliya Udagedara 2,731 Reputation points MVP
    2021-12-21T07:54:40.02+00:00

    You can do something like below.

    string applicationPath = Path.GetFullPath(AppDomain.CurrentDomain.BaseDirectory);  
    string saveFilePath = Path.Combine(applicationPath, "Temp.txt");  
    using var writer = new StreamWriter(saveFilePath, append: false);  
    writer.WriteLine(DateTime.Now.ToString());  
    writer.Close();  
      
    await Task.Delay(2000);  
      
    string[] lines = File.ReadAllLines(saveFilePath);  
    if (DateTime.TryParse(lines.ElementAt(0), out DateTime dateTime))  
    {  
        Console.WriteLine($"Saved: {dateTime}");  
        Console.WriteLine($"Current: {DateTime.Now}");  
    }  
      
    Console.ReadKey();  
    

    Output:
    159197-image.png

    0 comments No comments

  3. Karen Payne MVP 35,036 Reputation points
    2021-12-21T12:05:29.187+00:00

    Unless this is to learn working with read/writing to and from a file, the better option is to create a settings file. In the example below I use NuGet package Newtonsoft.Json.

    Settings file

    {  
      "LastRanDateTime": "2021-12-21T03:59:00.0877276-08:00",  
      "TrackBarValue": 30  
    }  
    

    This class is the container for things you want to save and restore.

    public class Setting  
    {  
        public DateTime? LastRanDateTime { get; set; }  
        public int TrackBarValue { get; set; }  
    }  
    

    Form code, save setting when closing the form and read them back in the Shown event.

    using System;  
    using System.ComponentModel;  
    using System.IO;  
    using System.Windows.Forms;  
    using Newtonsoft.Json;  
      
    namespace CodeSample  
    {  
        public partial class DemoForm : Form  
        {  
            private Setting _setting = new Setting();  
            // file will be in the application folder for settings  
            private readonly string _settingsFileName =   
                Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "settings.json");  
      
            public DemoForm()  
            {  
                InitializeComponent();  
      
                Shown += OnShown;  
                Closing += OnClosing;  
            }  
      
            private void OnShown(object sender, EventArgs e)  
            {  
                if (File.Exists(_settingsFileName))  
                {  
                    _setting = JsonConvert.DeserializeObject<Setting>(File.ReadAllText(_settingsFileName));  
      
                    if (_setting.LastRanDateTime.HasValue)  
                    {  
                        LastRanLabel.Text = $@"Last ran {_setting.LastRanDateTime.Value:h:mm:ss tt}";  
                    }  
      
                    trackBar1.Value = _setting.TrackBarValue;  
                }  
                else  
                {  
                    LastRanLabel.Text = "?";  
                }  
            }  
      
            private void OnClosing(object sender, CancelEventArgs e)  
            {  
                _setting.LastRanDateTime = DateTime.Now;  
                _setting.TrackBarValue = trackBar1.Value;  
                File.WriteAllText(_settingsFileName, JsonConvert.SerializeObject(_setting, Formatting.Indented));  
            }  
        }  
    }  
    
    0 comments No comments