I am currently writing a console application that deletes old log files, now I got that functionality working, I was trying to figure out how to execute a program with parameters from Command Prompt.
Example:
FileDeleter.exe days 3
where I'm running the program and telling it to delete 3 days worth of log files. Can these arguments be passed as variables into the code? I am not sure how this is accomplished.
Thanks for the help!
ArthurA
If you need more advanced parsing, there are of course libraries available
Best way to parse command line arguments in C#?
https://github.com/BizArk/BizArk3
http://fclp.github.io/fluent-command-line-parser/
your void main should take an array of strings as an arg:
static void Main(string[] args)
You can then parse the args as you see fit.
As #Neil N already mentionend, you have to define a your main method like this:
static void Main(string[] args)
args will then contain the arguments you passed.
If you run your program like this: FileDeleter.exe days 3, args[0] would contain the string "days" and args[1] would contain the string "3". Pay attention here that the latter one will be a string despite the fact that you passed a number. Therefor you might have to parse it to a number before using it.
I need guidance, someone to point me in the right direction. As the tittle says, I need to save information to a file: Date, string, integer and an array of integers. And I also need to be able to access that information later, when an user wants to review it.
Optional: File is plain text and I can directly check it and it is understandable.
Bonus points if chosen method can be "easily" converted to working with a database in the future instead of individual files.
I'm pretty new to C# and what I've found so far is that I should turn the array into a string with separators.
So, what'd you guys suggest?
// JSON.Net
string json = JsonConvert.SerializeObject(objOrArray);
File.WriteAllText(path, json);
// (note: can also use File.Create etc if don't need the string in memory)
or...
using(var file = File.Create(path)) { // protobuf-net
Serializer.Serialize(file, objOrArray);
}
The first is readable; the second will be smaller. Both will cope fine with "Date, string, integer and an array of integers", or an array of such objects. Protobuf-net would require adding some attributes to help it, but really simple.
As for working with a database as columns... the array of integers is the glitch there, because most databases don't support "array of integers" as a column type. I'd say "separation of concerns" - have a separate model for DB persistence. If you are using the database purely to store documents, then: pretty much every DB will support CLOB and BLOB data, so either is usable. Many databases now have inbuilt JSON support (helper methods, etc), which might make JSON as a CLOB more tempting.
I would probably serialize this to json and save it somewhere. Json.Net is a very popular way.
The advantage of this is also creating a class that can be later used to work with an Object-Relational Mapper.
var userInfo = new UserInfoModel();
// write the data (overwrites)
using (var stream = new StreamWriter(#"path/to/your/file.json", append: false))
{
stream.Write(JsonConvert.SerializeObject(userInfo));
}
//read the data
using (var stream = new StreamReader(#"path/to/your/file.json"))
{
userInfo = JsonConvert.DeserializeObject<UserInfoModel>(stream.ReadToEnd());
}
public class UserInfoModel
{
public DateTime Date { get; set; }
// etc.
}
for the Plaintext File you're right.
Use 1 Line for each Entry:
Date
string
Integer
Array of Integer
If you read the File in your code you can easily seperate them by reading line to line.
Make a string with a specific Seperator out of the Array:
[1,2,3] -> "1,2,3"
When you read the line you can Split the String by "," and gets a Array of Strings. Parse each Entry to int into an Array of Int with the same length.
How to read and write the File get a look at Easiest way to read from and write to files
If you really wants the switch to a database at a point, try a JSON Format for your File. It is easy to handle and there are some good Plugins to work with.
Mfg
Henne
The way I got started with C# is via the game Space Engineers from the Steam Platform, the Mods need to save a file Locally (%AppData%\Local\Temp\SpaceEngineers\ or %AppData%\Roaming\SpaceEngineers\Storage\) for various settings, and their logging is similar to what #H. Sandberg mentioned (line by line, perhaps a separator to parse with later), the upside to this is that it's easy to retrieve, easy to append, easy to overwrite, and I'm pretty sure it's even possible to retrieve File Size, which when combined with File Deletion and File Creation can prevent runaway File Sizes as this allows you to set an Upper Limit to check against, allowing you to run it on a Server with minimal impact (probably best to include a minimum Date filter {make sure X is at least Y days old before deleting it for being over Z Bytes} to prevent Debugging Data Loss {"Why was it over that limit?"})
As far as the actual Code behind the idea, I'm approximately at the same Skill Level as the OP, which is to say; Rookie, but I would advise looking at the Coding in the Space Engineers Mods for some Samples (plus it's not half bad for a Beta Game), as they are almost all written in C#. Also, the Programmable Blocks compile in C# as well, so you'll be able to use that to both assist in learning C# and reinforce and utilize what you already know (although certain C# commands aren't allowed for security reasons, utilizing the Mod API you'll have more flexibility to do things such as Creating/Maintaining Log Files, Retrieving/Modifying Object Properties, etc.), You are even capable of printing Text to various in Game Text Monitors.
I apologise if my Syntax needs some work, and I'm sorry I am not currently capable of just whipping up some Code to solve your issue, but I do know
using System;
Console.WriteLine("Hello World");
so at least it's not a total loss, but my example Code likely won't compile, since it's likely missing things like: an Output Location, perhaps an API reference or two, and probably a few other settings. Like I said, I'm New, but that is a valid C# Command, I know I got that part correct.
Edit: here's a better attempt:
using System;
class Test
{
static void Main()
{
string a = "Hello Hal, ";
string b = "Please open the Airlock Doors.";
string c = "I'm sorry Dave, "
string d = "I'm afraid I can't do that."
Console.WriteLine(a + b);
Console.WriteLine(c + d);
Console.Read();
}
}
This:
"Hello Hal, Please open the Airlock Doors."
"I'm sorry Dave, I'm afraid I can't do that."
Should be the result. (the "Quotation Marks" shouldn't appear in the readout {the last Code Block}, that's simply to improve readability)
I would like to extract the section of console output that occurs between two specific points in a program and store that into a variable. This would be executed in a loop many times. There is no need for output to be echoed into the regular console (if that makes things more efficient).
i.e.
foreach (Procedure p in procedures) {
BeginCapturingConsoleOutput();
p.Execute();
string procedureOutput = EndCapturingConsoleOutput();
}
The code on this page in MSDN does what I think you are looking for:
http://msdn.microsoft.com/en-us/library/16f09842.aspx
Basically, it sets the output stream to something that you define (in the case of the example, a file), performs some action, and at the end sets it back to the standard output stream.
I have a FORTRAN .exe file which runs and works ok, it will ask
user to input 1 or 2 and if 1 is entered it will do some calculation and if 2 is entered it does different kind of calculation.
I need to call this from C# code. I know how to run .exe file from C# but I can not pass 1 or 2 to the .exe
I have used different method but with no luck.
static void Main(string [] args)
{
string FileName = #"C:\......sco.exe";
process.StartInfo = new ProcessStartInfo(FileName,"3");
Process.Start(process.StartInfo); }
I really appreciate if some one knows how to fix this problems. I am new to C# and I can not rewrite the Fortran code since it is too comelicated.
Thank you for reading this post
I don't know C#, so I can't tell you how to do this in detail, but when running a fortran program from the command line, you can supply an extra file with arguments. Call it like this: mypgrogram.exe<inputs.ans
In your case, inputs.ans would contain a single 1 or 2. You can put each additional argument that the program asks for on a new line in this file.
We received a VS2010 C# project that calls the function Environment.ExpandEnvironmentVariables();
I understand how to use this with a string such as "%variable%\something.exe", but the code we received uses this string - "%%variable%%\something.exe"
What is the purpose of having two percent signs surrounding the variable? is this a variable pointing to a variable? if so how can this work without calling ExpandEnvironmentVariables twice?
%%variable%%\something.exe will expand to %<value of variable>%\something.exe.
You don't necessarily need a second call to ExpandEnvironmentVariables: the resulting string might get passed to an API that expands environment variables or it might get written to the registry as a REG_EXPAND_SZ or whatever.