How to append a new line to a file [duplicate] - c#

This question already has answers here:
Append lines to a file using a StreamWriter
(11 answers)
Closed 3 years ago.
I'm trying to create a code that asks for a user name and saves it in a text file. The problem is when I close the console app and try to run it again, it deletes all the information that was in the text file. Can anyone help me solve this problem?
public static void UserWriter(StreamWriter WriteNewLine)
{
bool EndOfWrite = true;
char Answer;
while (EndOfWrite)
{
Console.WriteLine("eneter a user name");
WriteNewLine.WriteLine(Console.ReadLine());
Console.WriteLine("did you finish ? Y/N");
Wrong: Answer = Convert.ToChar(Console.ReadLine());
switch (Answer)
{
case 'Y':
EndOfWrite = false;
break;
case 'N':
break;
default:
goto Wrong;
}
}
WriteNewLine.Close();
}
static void Main(string[] args)
{
string fileLoction = #"C:\project\user.txt";
StreamWriter WriteNewLine = new StreamWriter(fileLoction);
if (File.Exists(fileLoction))
{
WriteNewLine.Close();
WriteNewLine = File.AppendText(fileLoction);
UserWriter(WriteNewLine);
WriteNewLine.Close();
}
else
{
UserWriter(WriteNewLine);
WriteNewLine.Close();
}
}

Along with #metal answer, this shall do the job.
static void Main(string[] args)
{
string fileLoction = #"C:\project\user.txt";
StreamWriter WriteNewLine = new StreamWriter(fileLoction, true);
WriteNewLine = File.AppendText(fileLoction);
WriteNewLine.Close();
}

Related

Exception when PreBuildAction calls exe with command input

I have an issue with my (visual studio) pre-build action calling an executable, which requires a console input.
The code looks like:
using System;
using System.Diagnostics;
using System.Text;
namespace MyMinumumExample
{
internal class MinimumExample
{
private StringBuilder stdOutput = null;
private readonly string assemblyFilePath;
private readonly Process gitProcess = new Process()
{
StartInfo = new ProcessStartInfo()
{
FileName = "git",
RedirectStandardOutput = true,
UseShellExecute = false,
},
};
public MinimumExample(string path)
{
assemblyFilePath = path;
}
private static int Main(string[] args)
{
string path = args[0];
var program = new MinimumExample(path);
if (program.CheckIfFileIsDirty(path))
{
Console.WriteLine("Changes will be discarded after compiling. Do you want to proceed?");
while (true)
{
Console.Write("[y/n]: ");
ConsoleKeyInfo key = Console.ReadKey();
if (key.KeyChar == 'y')
break;
if (key.KeyChar == 'n')
return 1;
Console.WriteLine();
}
}
return 0;
}
private bool CheckIfFileIsDirty(string path)
{
string gitCmdArgs = string.Format("diff --shortstat -- {0}", path);
stdOutput = new StringBuilder();
gitProcess.StartInfo.Arguments = gitCmdArgs;
gitProcess.Start();
gitProcess.BeginOutputReadLine();
gitProcess.OutputDataReceived += GitProcessOutputHandler;
gitProcess.WaitForExit();
gitProcess.OutputDataReceived -= GitProcessOutputHandler;
if (gitProcess.ExitCode != 0) throw new Exception(string.Format("Process 'git {0}' failed with code {1}", gitCmdArgs, gitProcess.ExitCode));
return !string.IsNullOrWhiteSpace(stdOutput.ToString());
}
private void GitProcessOutputHandler(object sendingProcess, DataReceivedEventArgs outLine)
{
if (!string.IsNullOrWhiteSpace(outLine.Data))
{
stdOutput.Append(outLine.Data);
}
}
}
}
If I run this from cmd-shell or from a batch file everything works fine. If I put it into the pre build action, I get an exeption in line 38:
ConsoleKeyInfo key = Console.ReadKey();
The pre build action looks like:
call $(SolutionDir)MinimumExample.exe $(ProjectDir)dirtyExampleFile.cs
IF %ERRORLEVEL% GTR 0 (
EXIT 1
)
If I call the executable with start <exe> the example works, but I don't get the exit code of the exe (but probably of the new cmd shell).
Either, I can get the exit code of cmd shell to verify that the executable did exit cleanly, or I find a way to read keyboard input from the build event console.
Does anyone has an idea, how to solve this?
Best regards and thanks in advance!
I found the solution to get the exit code:
Using start with /wait option solved my problem.
PreBuildEvent is now:
start "Update version of $(ProjectName)" /wait $(SolutionDir)MinimumExample.exe $(ProjectDir)dirtyExampleFile.cs

Preventing user from inputting integers to string variables in C#

If I write the following code (inside the Main method):
Console.Write("First name: ");
student.FirstName = Console.ReadLine();
where FirsName is a property of Student class, how can I prevent the user from entering integer characters? Can this be done using try-catch block?
If you want to prevent user from "entering" Numeric Characters, you could do the following.
var value = new StringBuilder();
var run = true;
while (run)
{
var inputKey = Console.ReadKey(true);
switch (inputKey.Key)
{
case ConsoleKey.Enter:
run = false;
Console.WriteLine();
break;
case ConsoleKey.Backspace:
value.Append(inputKey.KeyChar);
break;
default:
if (!char.IsDigit(inputKey.KeyChar))
value.Append(inputKey.KeyChar);
Console.Write(inputKey.KeyChar);
break;
}
}
var name = value.ToString();
You were not very specific, but based on the data you gave you can do something like this using try catch:
class Program
{
static void Main(string[] args)
{
Student student = new Student();
try
{
Console.Write("First name: ");
student.FirstName = Console.ReadLine();
ValidateMyString(student.FirstName);
Console.ReadLine();
}
catch(Exception e)
{
throw e;
}
}
static void ValidateMyString(string s)
{
if (s.Any(char.IsDigit))
{
throw new FormatException();
}
}
}
Here a example in dotnetfiddle.

Simulate button click inside browser [duplicate]

This question already has answers here:
Simulating Key Press C#
(8 answers)
Closed 5 years ago.
I want to open default browser in my computer and then simulate to click the button. I have created a new console application as below:
class Program
{
[STAThread]
static void Main(string[] args)
{
var url = "http://google.com";
Process.Start(url);
Console.ReadKey();
}
}
Now what can I do? I found WebBrowser class but I think it's for browser control in windows forms app..
Get default browser using the below function
private static string GetStandardBrowserPath()
{
string browserPath = string.Empty;
RegistryKey browserKey = null;
try
{
//Read default browser path from Win XP registry key
browserKey = Registry.ClassesRoot.OpenSubKey(#"HTTP\shell\open\command", false);
//If browser path wasn't found, try Win Vista (and newer) registry key
if (browserKey == null)
{
browserKey = Registry.CurrentUser.OpenSubKey(#"Software\Microsoft\Windows\Shell\Associations\UrlAssociations\http", false); ;
}
//If browser path was found, clean it
if (browserKey != null)
{
//Remove quotation marks
browserPath = (browserKey.GetValue(null) as string).ToLower().Replace("\"", "");
//Cut off optional parameters
if (!browserPath.EndsWith("exe"))
{
browserPath = browserPath.Substring(0, browserPath.LastIndexOf(".exe") + 4);
}
//Close registry key
browserKey.Close();
}
}
catch
{
//Return empty string, if no path was found
return string.Empty;
}
//Return default browsers path
return browserPath;
}
Open url in default browser:
string url = "http://google.com";
string browserPath = GetStandardBrowserPath();
if (string.IsNullOrEmpty(browserPath))
{
MessageBox.Show("No default browser found!");
}
else
{
Process.Start(browserPath, url);
}

Check if parameter is already chosen in console

I'm writing a flesch index calculator and I want to be able to start my program with a console command and the .exe itself. I want to read in .txt files in the console with the command fleschIndexCalc.exe -f "path of the file" and then be able to select the calculation formula either for an english text with the parameter -e or a german text with -g.
When I start it with the console command: I type in the parameters by myself.
When I start it with the .exe: The program asks for the language and I just have to write g ore and press enter.
Now my question: how can I tell my program while starting it with the console that I already chose the language so it doesn't ask me for it again like I started it with the .exe?
Here's what I got:
(If you need more code from my FleschScore.cs ask for it :) )
namespace Flesch_Reading_Ease
{
public class Program
{
public static void Main(string[] args)
{
string fileName = string.Empty;
string[] parameters = new string[] { "-f", "-g", "-e" };
Console.WriteLine("Flesch Reading Ease");
Console.WriteLine("");
if (args.Length == 0)
{
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine("error!");
Console.ResetColor();
Console.WriteLine("no file found!");
Console.WriteLine("");
Console.Write("press any key...");
Console.ReadKey();
return;
}
foreach (string arg in args)
{
//------- WHAT TO WRITE HERE? -------
}
fileName = args[0];
FleschScore fs = new FleschScore(fileName);
fs.Run();
}
}
}
My method to choose the language looks like this:
private void SelectLanguage()
{
do
{
Console.WriteLine("choose language:");
Console.WriteLine("- german(g)");
Console.WriteLine("- english(e)");
string lang = Console.ReadLine();
switch (lang.ToUpper())
{
case "D":
_selectedLanguage = Language.German;
break;
case "E":
_selectedLanguage = Language.English;
break;
default:
_selectedLanguage = Language.Undefined;
Console.WriteLine("wrong input. Enter viable letter.");
Console.WriteLine("");
break;
}
} while (_selectedLanguage == Language.Undefined);
}
You basically loop through all the arguments and keep track of what's already entered. Then after that you check if you have all the info you need and pass everything as parameters to whatever method/class needs it.
bool isGerman = false;
bool isEnglish = false;
bool nextEntryIsFileName = false;
string filename = null;
foreach (string arg in args)
{
switch (arg)
{
case "-e":
isEnglish = true;
nextEntryIsFileName = false;
break;
case "-g":
isGerman = true;
nextEntryIsFileName = false;
break;
case "-f":
nextEntryIsFileName = true;
break;
default:
if (nextEntryIsFileName)
{
filename = arg;
nextEntryIsFileName = false;
}
break;
}
}
if (!(isEnglish ^ isGerman))
{
// Select language
}
if (String.IsNullOrEmpty(filename))
{
// Ask for filename
}
var language = ...
FleschScore fs = new FleschScore(language, fileName);
fs.Run();

Custom compiler flicker open then close

Im working with the custom compiler from MSDN website. When I try to compile/run some test code (drag and drop to .exe), the console window opens then closes instead of staying open until I choose to close it. How do I keep it open?
Source: http://msdn.microsoft.com/en-us/magazine/cc136756.aspx#S8
Program.cs
if (args.Length != 1)
{
// Display title, reset cursor to normal, add space
Console.WriteLine("Alt ver 1.0 (Alpha)");
Console.WriteLine();
Console.ReadLine();
try
{
Scanner scanner = null;
using (TextReader input = File.OpenText(args[0]))
{
scanner = new Scanner(input);
}
Parser parser = new Parser(scanner.Tokens);
CodeGen codeGen = new CodeGen(parser.Result, Path.GetFileNameWithoutExtension(args[0]) + ".exe");
}
catch (Exception e)
{
Console.Error.WriteLine(e.Message);
Console.ReadLine();
}
} //if
add a Console.ReadLine();
at the last inside the try block
try this
if (args.Length != 1)
{
// Display title, reset cursor to normal, add space
Console.WriteLine("Alt ver 1.0 (Alpha)");
Console.WriteLine();
Console.ReadLine();
try
{
Scanner scanner = null;
using (TextReader input = File.OpenText(args[0]))
{
scanner = new Scanner(input);
}
Parser parser = new Parser(scanner.Tokens);
CodeGen codeGen = new CodeGen(parser.Result, Path.GetFileNameWithoutExtension(args[0]) + ".exe");
}
catch (Exception e)
{
Console.Error.WriteLine(e.Message);
Console.ReadLine();
}
finally
{
Console.Readkey();
}
} //if
else
{
Console.WriteLine("no args");
Console.ReadKey();
}
EDIT:--- passing argument problem
i have made this program and it works perfectly as far as getting filename as arguments
please have a look
class Program
{
static void Main(string[] args)
{
if (args.Length > 0)
{
foreach (var arg in args)
{
Console.WriteLine(arg);
}
Console.ReadKey();
}
else
{
Console.WriteLine("NO ARGS");
var fileName = Console.ReadLine();
Main(new string[] { fileName });
}
}
}

Categories