Reputation: 23
I am trying to execute a certain string of commands on the start of a program, but it is not running. I have tried multiple things but my code right now looks something similar to this
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO;
namespace scriptname
{
public partial class Form1 : Form
{
public List<string> stringName = new List<string>();
public int stringCount = 0;
public Form1()
{
InitializeComponent();
}
//this code needs to run on app startup.
//--------------------------------------------------------------------------
public Awake()//this is from my knowledge with Unity
{
if (!Directory.Exists(@"C:\Example"))
{
Directory.CreateDirectory(@"C:\Example");
StreamWriter exampleText = new StreamWriter(@"C:\Example\Example.txt");
}
else
ReadFromFile();
}
//--------------------------------------------------------------------------
}
}
Note, I am using visual studio forms as my base.
I am trying to get the highlighted text to run on startup, but every time I check, the folder isn't made. All I can think is that the code isn't running.
I really don't know how to initialize it on startup, and I was hoping for some help. I can make it run on a button press, but then where is the fun of that?
Upvotes: 0
Views: 295
Reputation: 127603
The best way is to use the proper events to trigger on the point in time you want. There is a event that are actually fairly close to what Unity has with it's Awake
function. It is called OnLoad
and is run whenever the Load
event happens (which is right before the form is shown for the first time)
public partial class Form1 : Form
{
public List<string> stringName = new List<string>();
public int stringCount = 0;
public Form1()
{
InitializeComponent();
}
protected override void OnLoad(EventArgs e)
{
base.OnLoad(e); //You must remember to call base.OnLoad(e) when you override
if (!Directory.Exists(@"C:\Example"))
{
Directory.CreateDirectory(@"C:\Example");
StreamWriter exampleText = new StreamWriter(@"C:\Example\Example.txt");
}
else
ReadFromFile();
}
}
Upvotes: 2
Reputation: 690
Awake is something that works with unity. Thats not going to work on a Forms app
public Form1()
{
InitializeComponent();
Awake(); // This will call awake when the form starts. Consider renaming it
}
public Form1() is the constructor of this form class. It will always be called when ever you load the form. Everytime you run this form that method will be called. If you only want the code to be run once regardless of how many instances of the form you create at run time you should move the code to the Main method in the default Program.cs.
You should also not save or create directories right in the C: drive. You should use the App data folder.
Upvotes: 3