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

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

Related

Initialize form with a string as input parameter [duplicate]

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();

I cannot change image in picturebox c#

I have made a yatzy game in a console application, and I am currently trying to make one in a forms application.
This is what I have so far:
namespace Yatzy
{
public partial class Form1 : Form
{
public static Random kast = new Random();
public static int kast1 = kast.Next(1, 7);
public static int kast2 = kast.Next(1, 7);
public static int kast3 = kast.Next(1, 7);
public static int kast4 = kast.Next(1, 7);
public static int kast5 = kast.Next(1, 7);
public static int kast6 = kast.Next(1, 7);
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void pictureBox1_Click(object sender, EventArgs e)
{
if (kast1 == 1)
{
this.pictureBox_terning1.Image = new Bitmap(#"\Pics\terning1.png");
}
else if (kast1 == 2)
{
this.pictureBox_terning1.Image = new Bitmap(#"\Pics\terning2.png");
}
else if (kast1 == 3)
{
this.pictureBox_terning1.Image = new Bitmap(#"\Pics\terning3.png");
}
else if (kast1 == 4)
{
this.pictureBox_terning1.Image = new Bitmap(#"\Pics\terning4.png");
}
else if (kast1 == 5)
{
this.pictureBox_terning1.Image = new Bitmap(#"\Pics\terning5.png");
}
else if (kast1 == 6)
{
this.pictureBox_terning1.Image = new Bitmap(#"\Pics\terning6.png");
}
else
{
this.pictureBox_terning1.Image = new Bitmap(#"\Pics\terning0.png");
}
}
}
}
As you can see, I define the "kast1" and such in the form, and depending on the outcome, it should display different images in the picturebox. I have looked at every post I could find, and all of the solutions were fuss.
I have tried without "this." and I've tried with "= image.FromFile("Pics\terning#.png");"
Nothing works.
There is no need to use Bitmap object just to load images in the PictureBox.Perhaps the more cleaner way of loading images is by using the Load Method of PictureBox.
If I assume the images are in same directory as your application,enclosed in another folder,this would have done the job easily;
this.pictureBox_terning1.Load(#"\Pics\terning1.png");
The Load method requires a valid path that points to an image as argument,and with this there is no need to call Refresh after loading each image.It doesn't matter if the path is absolute or relative,but the thing that matters is that the path should point to an image.
But I would suggest you to create an absolute path to your executable like this;
string apppath=Application.StartupPath;
string imagepath=#"\Pics\terning1.png";
this.pictureBox_terning1.Load(apppath+imagepath);
As you mentioned that even if no errors are encountered,the images are not being loaded,for such a case debugging would be an ideal technique to find where the program runs out of order.
You probably need to call Refresh() on the picturebox control after you change picture source.
It is most likely that the images you want to load are not at the path you are looking at.
image.FromFile("Pics\terning#.png");
Expects that your images reside in {youprojectfolder}\bin\DebugORRelease\Pics.
new Bitmap(#"\Pics\terning1.png");
Expects that you images reside in {most likely c:}\Pics.
So i would suggest to check this first and if this does not work add a Breakpoint (F9) and start debugging (F5) see MSDN for an introduction in debugging
I would also suggest you to replace your if, else if construct with a switch.
Try this code, which I have tried and works(it will get the bin directory of your app then you can replace folders with image directory):
private void pictureBox1_Click(object sender, EventArgs e)
{
string path = AppDomain.CurrentDomain.BaseDirectory;
string path1 = path.Replace(#"\bin\Debug\", #"\Pics\");
if (kast1 == 1)
{
this.pictureBox_terning1.Image = new Bitmap(path1 + "terning1.png");
}
//rest of the code
}
And if you dont like replacing then set your pictures to be copied to bin directory by
right clicking on image -> properties -> Copy to output directory -> copy
always
.

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.

open file directly

I created a text editor in C# and I use a special file extension for the XML file that my program uses. When I use "Open With..." from the Windows context menu, my program doesn't read the file and I get an error.
How do I fix this?
In your Main() method, you need to capture the file name:
static void Main(string args[])
{
string fileName;
if (args.Length > 0)
fileName = args[0];
...
}
Then you'll need to pass fileName to the code that opens the file. How you do that is up to you.
If your Main() method has no parameters, just add the string args[] parameter and the runtime will take care of populating the array with the commandline parameters.
If you are already doing that, then this is probably a SuperUser question.
but the Main like that
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form1());
}
it doesn't have any parameters
you can use this simple code to answer me
private void button1_Click(object sender, EventArgs e)
{
richTextBox1.Text = File.ReadAllText(#"d:\wifi.txt");
}
the text viewed in the richtextbox1

Categories