I have a program that writes data to a .txt
file(Notepad) in a temporary location. This program changes the value and runs it multiple times. Unfortunately, each time that happens, you have to close and reopen the .txt
file.
Is there any way to solve this?
public class Program
{
public static void Main()
{
var client = new Client();
var service = new Service();
client.Operation(service);
}
}
public class Client
{
public void Operation(IService service)
{
service.Write("Hello C# world");
}
}
public interface IService
{
public void Write(string message);
}
public class Service : IService
{
private const string Path = @"C:\Temp/tempFile.txt";
public void Write(string message)
{
using var writer = new StreamWriter(Path);
writer.WriteLine(message);
}
}
The reason we need this method is for learning purposes.
To practice the decorator pattern, I'm writing a temporary program that supports compression and encryption. I use a .txt
file because it's really simple and only needed.
It doesn't have to be a .txt
file, as you just need to visually verify it.
CodePudding user response:
You're updating the file just fine with your code. (You can verify that by looking at the file's size in File Explorer when you write into it.)
It's just that Notepad, the program you're viewing it with, isn't smart enough to check whether the file has updated on disk and refresh its view of it accordingly.
You can use an alternative editor, such as Notepad , Sublime Text, Visual Studio Code, any JetBrains IDE, whatever, that is smart enough to check whether the file should be refreshed.
You could also write your own program to re-read and show the contents of the file in real-time.