Initialize form with a string as input parameter [duplicate] - c#

This question already has answers here:
How do I pass command-line arguments to a WinForms application?
(6 answers)
Windows form application command line arguments
(1 answer)
Closed 5 years ago.
My c# program is a text editor which needs file name as an input parameter. In other words, I would like to start the c# EXE from a BAT file specifying which file to open. For example: "call C:\Temp\MyDotNetApp File1", where 'File1' is the input parameter for the program in C#.
Is this possible in C#? I can't find any tutorial on internet.
My code:
namespace CSVEditor{
public partial class Form1 : Form {
public static string TAG = "";
public static string FileLinnk = "";
}
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
//Input file to read
File = "File1";// <----- This needs to be the input parameeter from BAT file.
//
FileLink = #"c:\temp" + File + ".csv";
ReadCSV(FileLink);
}
Cheers.

Just use Environment.GetCommandLineArgs;
string[] args = Environment.GetCommandLineArgs();

Related

How to save an username in Winforms? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 1 year ago.
The community is reviewing whether to reopen this question as of 1 year ago.
Improve this question
I am trying to save the username entered in the "enter playername" field in order to create a highscore list, can anyone help me with that ?
namespace TikTakTo
{
public partial class Anmeldung : Form
{
public Anmeldung()
{
InitializeComponent();
}
private void button_play_Click(object sender, EventArgs e)
{
Form1.setSpielerName(Spieler_1.Text, Spieler_2.Text);
Form1 frm = new Form1();
frm.Show();
this.Hide();
}
private void Spieler_2_KeyPress(object sender, KeyPressEventArgs e)
{
if (e.KeyChar.ToString() == "\r")
button_play.PerformClick();
}
}
}
Most recommanded option for windows-forms applications is a settings file located in the Properties folder.
The data there can be saved per-user and per-application, and stored in the application's AppData folder.You can read the settings-table fields, change their values and save your changes.
e.g:Properties.Settings.Default["SomeProperty"] = "Some Value";Properties.Settings.Default.Save();
Read this question for more info.
Basically you have two options, you can either save the info to file, or save it to database. This should help you: Best way to store data locally in .NET (C#)
Always try to make your own search before asking a question!
you can write in txt file in your project folder , and after restarting the app, you can control the file in that location , if its exist you can read data and put the form.
like a cookie.
example code.
public static string _debugPath { get { return Path.GetDirectoryName(System.Reflection.Assembly.GetEntryAssembly().Location); } }
public static void WriteToText(string txt)
{
DateTime _dt = DateTime.Now;
using (StreamWriter wr = File.AppendText(Path.Combine(_debugPath, "Info.Inc")))
{
wr.WriteLine(txt+"|");
wr.Close();
}
}
public static bool ReadInfo()
{
FileInfo fi = new FileInfo(Path.Combine(_debugPath , "Info.Inc"));
if (fi.Exists)
{
using (StreamReader rd = new StreamReader(Path.Combine(_debugPath , "Info.Inc")))
{
//take data in here and put the form.
}
}
}

How do you export/import variables from one form to another in C#? [duplicate]

This question already has answers here:
Send values from one form to another form
(20 answers)
Closed 1 year ago.
I made 2 forms in C# and I need to export some variables in one of them and import them to another. I keep hitting google but All I get is something about 'Environment.GetEnvironmentVariable'. Is this the right method to do?
You can pass your value one form to another form. you don't need to pass variable.
Exporter Activity code:
Intent i = new Intent(this,typeof(Activity2));
i.PutExtra("Name",txt_Name.Text.ToString());
StartActivity(i);
Importer Activity code:
string name = Intent.GetStringExtra("Name");
txt_Result.Text ="Hello, "+name;
I'm not sure what do you want, but you could pass arguments like:
Form form2 = new Form(argument); //pass an argument
form2.Show();
this.Hide();
And in the second form is like:
public Form2(string argument){
InitializeComponent();
// do whatever you want with passed argument
}
Or you can create a public static variable, like:
// in the main form
public static int value = 2;
And in the second form:
int value2 = Form.value;
I hope this helps you

How to use the function to get location of executable path? [duplicate]

This question already has answers here:
How can I get the application's path in a .NET console application?
(30 answers)
Closed 6 years ago.
I created a Form Application and I tried to get the executable path, and I find this :
System.Reflection.Assembly.GetExecutingAssembly().Location;
System.IO.Path.GetDirectoryName;
but when I puted in my code I had a lot of errors .
This is my code :
namespace inst
{
public class Program
{
System.Reflection.Assembly.GetExecutingAssembly().Location;
System.IO.Path.GetDirectoryName;
[STAThread]
static void Main()
{
}
}
It is right where I placed it? And I want to use that location to find a text file, to be able to change, like here:
private void Form1_Load(object sender, EventArgs e)
{
this.Text = File.ReadLines(Program.Path)
.First(x => x.StartsWith("Title=\""))
.Split(new[] { '=', '"' }, StringSplitOptions.RemoveEmptyEntries)[1];
}
The Path is the location of the file text.
So I want to get de location of executable where is a file test.txt, put the location in a variabile and use that variabile in form1 and form2, in my case
Just put the line System.Reflection.Assembly.GetExecutingAssembly().Location; in the Form1_Load method. and use what it returned. By the way if the file you are trying to access is in the same directory as the assembly there is no need to obtain the path. The paths are relative the executing assembly path.
Also in WinForm application it is better to use Application.StartupPath to get the path.
It is not allowed to have a code outside of a method, except of declarations, by the way like yours is:
System.Reflection.Assembly.GetExecutingAssembly().Location;
System.IO.Path.GetDirectoryName;
And also the compiler wouldn't like that it is not a statement at all. you should do something like var value = Something; and not just Something;
Simply declare a String
private string Path
{
get { return Assembly.GetExecutingAssembly().Location.ToString();}
}
then use it where you want
Edit: for the directory path it's this:
private string Path
{
get {return AppDomain.CurrentDomain.BaseDirectory.ToString();}
}
your code will be
namespace inst
{
public class Program
{
private string Path
{
get {return AppDomain.CurrentDomain.BaseDirectory.ToString();}
}
[STAThread]
static void Main()
{
}
}
and you function (who is in the same class Program)
private void Form1_Load(object sender, EventArgs e)
{
this.Text = File.ReadLines(Path)//here the string with the directory path
.First(x => x.StartsWith("Title=\""))
.Split(new[] { '=', '"' }, StringSplitOptions.RemoveEmptyEntries)[1];
}
if you want the variable Path accessible in all other class you can add a static class and add the string declaration as public and you could use it everywhere like this yourStaticClassName.Path

Error "Does not contain a static "Main" Method suitable for an entry point [duplicate]

This question already has answers here:
"does not contain a static 'main' method suitable for an entry point"
(10 answers)
Closed 9 years ago.
I got this Error when I try to compile a sourcecode with CodeDom
Does not contain a static "Main" Method suitable for an entry point!
I already googled it and read other answers here, but I dont know how to fix it.
Can someone please help me?
Here is my source code :
http://picz.to/image/ao5n
^ private void button2_Click(object sender, EventArgs e)
{
SaveFileDialog d = new SaveFileDialog();
d.Filter = "Executable (*.exe)|*.exe";
if (d.ShowDialog() == DialogResult.OK)
{
string source = Properties.Resources.source;
CompilerParameters param = new CompilerParameters();
param.CompilerOptions += "/target:winexe" + " " + "/win32icon:" + "\"" + textBox1.Text + "\"";
param.GenerateExecutable = true;
param.ReferencedAssemblies.Add("System.Windows.Forms.dll");
param.ReferencedAssemblies.Add("System.dll");
param.OutputAssembly = d.FileName;
StringBuilder Temp = new StringBuilder();
String InputCode = String.Empty;
InputCode = "MessageBox.Show((1 + 2 + 3).ToString());";
Temp.AppendLine(#"using System;");
Temp.AppendLine(#"using System.Windows.Forms;");
Temp.AppendLine(#"namespace RunTimeCompiler{");
Temp.AppendLine(#"static void Main(string[] args){");
Temp.AppendLine(#"public class Test{");
Temp.AppendLine(#"public void Ergebnis(){");
Temp.AppendLine(InputCode);
Temp.AppendLine(#"}}}}");
CompilerResults result = new CSharpCodeProvider().CompileAssemblyFromSource(param, Temp.ToString());
if (result.Errors.Count > 0) foreach (CompilerError err in result.Errors) MessageBox.Show(err.ToString());
else MessageBox.Show("Done.");
}
}
All C# programs need to contain the Main() method. Essentially this is where the program starts. The code you posted is just a small part of the entire application. You must have removed the location where main had been residing.
MSDN Article on Main
Updated for comments:
A new Windows Form App has a Program class that instantiates the form that you want.
static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form1());
}
}
Try copying that over to a new file called program.cs. Make sure that Form1 now points to the form you created in the applications.
Paste this into your class -- if you still get an error, you need to paste the entire class in question, not just a screen capture of the event handler for a button click.
static void Main(string[] args)
{
//do nothing
}
The code you've posted is the click event for a button. A button is usually on a form, and the form must be initialized. If you create a Windows Forms Application it will create a file Program.cs that contains a Main method that starts your form.
When you start a program, the computer needs to know where to actually start running code, that's what the Main() method is for. It is required to run, and that's the error you are receiving.

C# : getting folder name when right click on it

I am developing a windows application, I need to get the Folder name while right clicking on the Folder to do some operations on it .
So far I did the following :
Made a registry subkey in HKKEY_CLASS_ROOT\Folder\shell\(my program name)
Made a registry subkey of my program name\command [the path of my program]
now I made the registry key to be displayed in folder context menu. And in my application I did the following :
1- in program.cs
static void Main(string[] args)
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Form1 p = new Form1();
if (args.Length > 0)
{
p.pathkey = args[0];
}
Application.Run(p);
}
2- in my form1 :
private string _pathkey;
public string pathkey
{
get { return _pathkey; }
set { _pathkey = value; }
}
private void Form1_Load(object sender, EventArgs e)
{
if (this.pathkey != null)
{
textBox1.Text=pathkey;
}
}
finally :
now when I right click on a folder lets say for example called NEW. then textbox3.text = C:\NEW , so far it works fine but if the folder name is New Folder then textbox3.text = C:\New only not C:\New Folder and that is my problem if args.length > 0 it does only display the the lenght 0 not the full path.
You need to put the %0 in the registry in quotes to force the entire path to be treated as a single argument.
Otherwise, the spaces are treated as argument separators.
You could also call String.Join(" ", args) to manually recombine all of the arguments, but the first way is better.

Categories