user2516578
user2516578

Reputation: 19

Create .txt file and open in Notepad without saving

I need to create a .txt file in C# .

Is there a way (and how to do?) to create a file and open it in Notepad, but without saving in somewhere first? The user would save it after he checks it.

Upvotes: 0

Views: 1441

Answers (2)

Caio Lopes
Caio Lopes

Reputation: 1

I created a way (I don't know if it already exists), using System.Diagnostics and System.Reflection libraries. My code is:

File.WriteAllText($@"{Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location)}\exampleDoc.txt", "information inside file");
while (!File.Exists($@"{Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location)}\exampleDoc.txt")) { }
Process.Start($@"{Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location)}\exampleDoc.txt");

while (Process.GetProcesses().Where(prc => { try { return prc.MainWindowTitle.Contains("exampleDoc.txt"); } catch { return false; } }).Count() == 0) { }
File.Delete($@"{Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location)}\exampleDoc.txt");

Upvotes: 0

sommmen
sommmen

Reputation: 7608

No not really, i've seen some programs that do this like so, but its not ideal:

  1. Create a temporary file, most programs use the temp directory you get there by using %temp% or C:\Users\{username}\AppData\Local\Temp so e.g. File.Create(@"C:\Users\{username}\AppData\Local\Temp\myTempFile.Txt")
  2. Open the file with notepad. (File.Open(@"C:\Users\{username}\AppData\Local\Temp\myTempFile.Txt")) The user makes the change and saves
  3. Your program checks the file to see if any edits were made.
  4. if any edits have been made, you can prompt the user to save the file to the actual location. e.g. !string.IsNullOrWhiteSpace(File.ReadAllText(@"C:\Users\{username}\AppData\Local\Temp\myTempFile.Txt"))
  5. If the user wants to save the file, the file gets copied to the real location File.Copy(@"C:\Users\{username}\AppData\Local\Temp\myTempFile.Txt", @"c:\myRealPath\MyRealFileName.txt"

Upvotes: 1

Related Questions