Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
452 views
in Technique[技术] by (71.8m points)

c# - How do I save data from a variable to a file?

So I have a method, and I want to keep track of how many times it gets called.

using System;

public class Program
{
    public static int useCount;

    public static void Main()
    {
        Add(1, 3);
        Add(2, 4);
        Console.WriteLine(useCount);
    }

    public static int Add(int A, int B)
    {
        int sum = A + B;
        useCount++;
        return sum;
    }
}

Is there a way to save useCount to a file or something? In addition, if I can save it to a file, can it be updated? Like if the useCount was 4, but then the program gets restarted, and useCount is 7, can I add that to the saved file where it shows 11, instead of overwriting the previous useCount of 4?

Hope I'm coherent enough.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You can write the values into a file. Write on the top of your program "using System.IO" to implement the library.

using System.IO; //implement the library of the file operations.

if(File.Exists("<Here you puth path>"))
{
int value = int.Parse(File.ReadAllText("<Here you put path>")); /* gives the current number value of on the file */
value += useCount; //adds to the current value of the file
File.WriteAllText("<Here you put path>", value.ToString()); //updates the value
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...