C# error CS0103 when using methods in different classes - c#

I'm a newbie in C# and not native English (sorry for that); I am using Visual Studio 2017 using WinForm application.
To test some features to be added in an already existing project, I have created a new Winform application. This simple software writes and reads strings to and from a file. So, in the form I have 2 textboxes and 3 buttons: Save to file, Read from file and Update. To reduce the confusion in the bigger project, I've decided to split the methods in different classes: each one does one job and the form script has the minimum quantity of code possible.
The 3 .cs files (clases) are:
The form partial class,
SaveFile class, where the job to save the string to a text file is carried out,
OpenFile class, where the job to read the text file returning the lines in a list of strings.
All the 3 classes have been created and added to the project ProvaSalvataggioFile2.
So, the form class is (take note only of the methods' name, I have written all the code for completeness, if someone wants to test the code)
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO;
namespace ProvaSalvataggioFile2
{
public partial class MainForm : Form
{
public MainForm()
{
InitializeComponent();
}
private void btnSave_Click(object sender, EventArgs e)
{
string inputString = tbInputText.Text;
if (inputString.IsValidString())
{
inputString.SaveToFile();
}
else
{
MessageBox.Show("The input string is not valid: please insert a valid string",
"Empty or null input string",
MessageBoxButtons.OK,
MessageBoxIcon.Exclamation);
tbInputText.Focus();
}
}
private void btnOpenFile_Click(object sender, EventArgs e)
{
List<string> textFileContent = new List<string>();
textFileContent = OpenTextFile();
tbFileText.Text = string.Join(Environment.NewLine, textFileContent);
}
private void btnUpdate_Click(object sender, EventArgs e)
{
if (File.Exists(fileName))
{
List<string> textReadFromFile = new List<string>();
textReadFromFile = File.ReadAllLines(fileName).ToList();
tbFileText.Text = string.Join(Environment.NewLine, textReadFromFile);
}
}
}
}
The SaveFile class is
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO;
namespace ProvaSalvataggioFile2
{
public static class SaveFile
{
public static bool IsValidString(this string stringToValidate)
{
bool result = true;
if (string.IsNullOrEmpty(stringToValidate))
{
result = false;
}
return result;
}
public static bool SaveToFile(this string stringToSave)
{
bool result = true;
//bool savedfile;
DialogResult messageBoxResult;
SaveFileDialog saveFileDialog1 = new SaveFileDialog();
//saveFileDialog1.InitialDirectory = #"C:\";
saveFileDialog1.Title = "Save text Files";
saveFileDialog1.CheckFileExists = false;
saveFileDialog1.OverwritePrompt = false;
saveFileDialog1.CheckPathExists = true;
saveFileDialog1.DefaultExt = "txt";
saveFileDialog1.Filter = "Text files (*.txt)|*.txt|All files (*.*)|*.*";
saveFileDialog1.FilterIndex = 1;
saveFileDialog1.RestoreDirectory = true;
if (saveFileDialog1.ShowDialog() == DialogResult.OK)
{
if (File.Exists(saveFileDialog1.FileName))
{
messageBoxResult = MessageBox.Show("The file is already existing: do you want:\n\t\u22c5OVERWRITE the file [YES]\n\t\u22c5APPEND data in the file [NO]\n\t\u22c5Use another file [CANCEL]",
"Overwrite file",
MessageBoxButtons.YesNoCancel,
MessageBoxIcon.Asterisk,
MessageBoxDefaultButton.Button3);
if (messageBoxResult == DialogResult.Yes)
{
messageBoxResult = MessageBox.Show(("Are you sure to overwrite the file in\n" + saveFileDialog1.FileName),
"Sure to overwrite file?",
MessageBoxButtons.OKCancel);
if (messageBoxResult == DialogResult.OK)
{
try
{
File.WriteAllText(saveFileDialog1.FileName, stringToSave);
result = true;
}
catch
{
result = false;
}
}
}
else if (messageBoxResult == DialogResult.No)
{
//MessageBox.Show(("Message to save: \"" + stringToSave + "\"\nin \"" + saveFileDialog1.FileName));
try
{
File.AppendAllText(saveFileDialog1.FileName, (Environment.NewLine + stringToSave));
result = true;
}
catch
{
result = false;
}
}
else
{
messageBoxResult = MessageBox.Show("Please enter a new filename",
"Save in a new file",
MessageBoxButtons.OKCancel);
if (messageBoxResult == DialogResult.OK)
{
stringToSave.SaveToFile();
}
}
}
else
{
File.WriteAllText(saveFileDialog1.FileName, stringToSave);
result = true;
}
}
return result;
}
}
}
And the OpenFile class is:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO;
namespace ProvaSalvataggioFile2
{
public class OpenFile
{
public string fileName { get; set; }
public List<string> OpenTextFile()
{
List<string> textReadFromFile = new List<string>();
//textReadFromFile = new List<string>();
OpenFileDialog openFileDialog1 = new OpenFileDialog();
openFileDialog1.CheckPathExists = true;
openFileDialog1.CheckFileExists = true;
openFileDialog1.RestoreDirectory = true;
openFileDialog1.Filter = "Text files (*.txt)|*.txt|All files (*.*)|*.*";
openFileDialog1.FilterIndex = 1;
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
fileName = openFileDialog1.FileName.ToString();
textReadFromFile = File.ReadAllLines(openFileDialog1.FileName).ToList();
}
return textReadFromFile;
}
}
}
Now, if I put all the methods in the form class, all works just fine, with no problems (the application is stupid, only made to test the logic behind). But if I split the code in the 3 classes, I have:
Error CS0103 The name 'OpenTextFile' does not exists in the current context ProvaSalvataggioFile2 Form1.cs 41
Error CS0103 The name 'fileName' does not exists in the current context ProvaSalvataggioFile2 Form1.cs 47
Error CS0103 The name 'fileName' does not exists in the current context ProvaSalvataggioFile2 Form1.cs 50
So there must be some problem related with the splitting in classes. I have tried googling the error, but it seems that this error comes out in very different occasions and for different reasons (nothing in common with mine). I argue that I have missed something in the process of adding the new class or in the code defining the class.
I repeat myself, if I copy and paste the methods in the form class, the application works perfectly, but the same methods put in a separate class (but in the same file of the form class) doesn't.

The problem here is that you are trying to access members of the OpenFile class within the MainForm class. Initialize an instance of OpenFile and keep it in a variable within your MainClass to reuse
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO;
namespace ProvaSalvataggioFile2
{
public partial class MainForm : Form
{
// Initialize OpenFile
private readonly OpenFile openFile = new OpenFile();
public MainForm()
{
InitializeComponent();
}
private void btnSave_Click(object sender, EventArgs e)
{
string inputString = tbInputText.Text;
if (inputString.IsValidString())
{
inputString.SaveToFile();
}
else
{
MessageBox.Show("The input string is not valid: please insert a valid string",
"Empty or null input string",
MessageBoxButtons.OK,
MessageBoxIcon.Exclamation);
tbInputText.Focus();
}
}
private void btnOpenFile_Click(object sender, EventArgs e)
{
List<string> textFileContent = new List<string>();
textFileContent = openFile.OpenTextFile(); // Open Text File via openFile variable
tbFileText.Text = string.Join(Environment.NewLine, textFileContent);
}
private void btnUpdate_Click(object sender, EventArgs e)
{
if (File.Exists(openFile.fileName)) // Validate file exists via openFile.fileName property
{
List<string> textReadFromFile = new List<string>();
textReadFromFile = File.ReadAllLines(fileName).ToList();
tbFileText.Text = string.Join(Environment.NewLine, textReadFromFile);
}
}
}
}
You can also reduce your code by changing your IsValidString method to an extension method
public static bool IsValidString(this string stringToValidate) => !string.IsNullOrEmpty(stringToValidate)
I would recommend somewhat redesigning the code because there are potential bugs waiting to be found by using one class, I.E OpenFile, for opening and checking file contents. What if the file isn't opened and fileName is an empty string for example.
See the following MSDN article on classes to understand them more in-depth, and how the interact with each other.
Refactored Code
I have refactored the code to make it a bit more manageable and readable, please see below.
Here's a new class called TextFile which you can store the filename and contents in.
namespace ProvaSalvataggioFile2
{
public class TextFile
{
public TextFile(string fileName, string contents)
{
FileName = fileName;
Contents = contents;
}
public string FileName { get; set; }
public string Contents { get; set; }
}
}
Your OpenFile class is actually named pretty well, it has quite a good separation of concerns - meaning that on first glance I can see that it's a class which should only be used to open files, though you could go a step further and abstract the UI code away which couples you to Win Forms. OpenTextFile now returns a TextFile object
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO;
namespace ProvaSalvataggioFile2
{
public class OpenFile
{
public TextFile OpenTextFile()
{
TextFile textFile;
OpenFileDialog openFileDialog1 = new OpenFileDialog();
openFileDialog1.CheckPathExists = true;
openFileDialog1.CheckFileExists = true;
openFileDialog1.RestoreDirectory = true;
openFileDialog1.Filter = "Text files (*.txt)|*.txt|All files (*.*)|*.*";
openFileDialog1.FilterIndex = 1;
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
string fileName = openFileDialog1.FileName.ToString();
string textReadFromFile = File.ReadAllText(openFileDialog1.FileName);
textFile = new TextFile(fileName, textReadFromFile);
}
return textFile;
}
}
}
And of course, MainForm has to be updated to take the new object into consideration, I've removed duplicated code, reused your OpenFile class and introduced a RefreshTextFile method for setting the label text - this time you don't have to worry about file names being valid.
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO;
namespace ProvaSalvataggioFile2
{
public partial class MainForm : Form
{
private readonly OpenFile openFile = new OpenFile();
public MainForm()
{
InitializeComponent();
}
private void btnSave_Click(object sender, EventArgs e)
{
string inputString = tbInputText.Text;
if (inputString.IsValidString())
{
inputString.SaveToFile();
}
else
{
MessageBox.Show("The input string is not valid: please insert a valid string",
"Empty or null input string",
MessageBoxButtons.OK,
MessageBoxIcon.Exclamation);
tbInputText.Focus();
}
}
private void btnOpenFile_Click(object sender, EventArgs e)
{
RefreshTextFile();
}
private void btnUpdate_Click(object sender, EventArgs e)
{
RefreshTextFile();
}
private void RefreshTextFile()
{
TextFile textFile = openFile.OpenTextFile();
tbFileText.Text = textFile?.Contents;
}
}
}
Please note I have refactored this using Notepad++ and haven't put it through a compiler.

Your Form class doesn't know where or what OpenTextFile() is, same goes for fileName.
You need to create an instance of the object you want to use.
Try adding this code to MainForm:
private OpenFile _openFile;
public MainForm()
{
this._openFile = new OpenFile();
InitializeComponent();
}
This creates a new instance of the OpenFile class that MainForm can now use.
You can also make OpenFile static but that is not considered to be a best practice.
Please note that since your OpenFile.fileName is not initialized that you might want to add something like this as well.
public OpenFile(string initialFileName = "defaultFilename"){
this.fileName = initialFileName;
}
you can then even specify the filename in MainForm by providing it as an argument.
Or if you don't want to set an argument you can do a null check before reading/using the fileName.
for more info about objects and constructor see:
https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/objects
https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/constructors

Related

Cannot apply "Visible" method from a global class to multiple winforms in C#

I need your help with something I am dealing with. I am new to c# and I am creating a winforms application with multiple forms in it. There's a piece of code that needs to be present on all forms but since I don't want to just copy and paste it in every form, I created a class that stores that code and then I only want to call that class.
My global code that needs to be repeated is as follows,
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace Delfoi_Tourist_Guide
{
public class Login_User
{
public void CheckStatus()
{
DialogResult dialogResult = MessageBox.Show("Do your want to disconnect?;", "Disconnect", MessageBoxButtons.YesNo);
if (dialogResult == DialogResult.Yes)
{
Welcome form1 = new Welcome();
form1.Show();
this.Visible = false;
}
else if (dialogResult == DialogResult.No)
{
MessageBox.Show("Συνεχίστε την περιήγηση σας!!!");
}
}
}
}
I am also providing you a portion of code from another form in which I am applying my global code
private void linkLabel1_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
{
Login_User loginUser = new Login_User();
loginUser.CheckStatus();
}
My problem is that I can't transfer the "Visible" method from my global class to the other classes. I suppose this happens because my global class isn't attached to a winform. It's just a piece of code that's been used globally. What am I doing wrong???
try this
public static void CheckStatus(System.Windows.Form currentForm)
{
.....
currentForm.Visible = false;
`````
}
and call it
.....
Login_User.CheckStatus(this);
.....
Your problem occurs because the keyword "this" applies as property to the form, not the class. In your case you have to pass an instance of the form as parameter in your CheckStatus method. But since you want this to apply in all of your forms, you have to type the word "Form". Below I am providing you the answer,
Your Global Code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace Delfoi_Tourist_Guide
{
public static class Login_User
{
public static void CheckStatus(Form currentForm)
{
DialogResult dialogResult = MessageBox.Show("Do your want to disconnect?;", "Disconnect", MessageBoxButtons.YesNo);
if (dialogResult == DialogResult.Yes)
{
Welcome form1 = new Welcome();
form1.Show();
currentForm.Visible = false;
}
else if (dialogResult == DialogResult.No)
{
MessageBox.Show("Συνεχίστε την περιήγηση σας!!!");
}
}
}
}
and then you have to apply your global code to your desired forms, as follows.
Please note that you have to set the whole class as static in order for it, to work.
Apply Global Code To Forms
private void linkLabel1_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
{
Login_User.CheckStatus(this);
}

"ExportToDataGridView" Does not exist in .NET GemBox

Ive been trying to find why this happend but for some reason .net of gembox.spreadsheet.winformutilities wont provide ExportToDataGridView on the code:
using System.Windows.Forms;
using GemBox.Spreadsheet;
using GemBox.Spreadsheet.WinFormsUtilities;namespace Excel
{
public partial class UserControl1 : UserControl
{
private void bunifuFlatButton2_Click(object sender, EventArgs e)
{
OpenFileDialog open = new OpenFileDialog();
open.Filter = "Al files (*.*)|*.*|";
open.FilterIndex = 1;
if (open.ShowDialog()== DialogResult.OK)
{
ExcelFile ef = new ExcelFile();
ExcelWorksheet ws = ef.Worksheets.Add("Export");
DataGridViewConverter.***ExportToDataGridView***(ef.Worksheets.ActiveWorksheet, this.dataGridView1, new ExportToDataGridViewOptions() { ColumnHeaders = true });
}
}
}
}
thank you for your answer in advance!
The problem occurred because of the name collision:
namespace Excel
{
public partial class UserControl1 : UserControl
{
public static class DataGridViewConverter
{
}
}
}
So there are two classes of same name:
Excel.UserControl1.DataGridViewConverter
GemBox.Spreadsheet.WinFormsUtilities.DataGridViewConverter
The solution is to either use the class's full name, or you could define an alias name, for example:
// ...
using System.Windows.Forms;
using GemBox.Spreadsheet;
using GemBoxDataGridViewConverter = GemBox.Spreadsheet.WinFormsUtilities.DataGridViewConverter;
namespace Excel
{
public partial class UserControl1 : UserControl
{
private void bunifuFlatButton2_Click(object sender, EventArgs e)
{
GemBoxDataGridViewConverter.ExportToDataGridView(...);
}
}
}
Also as an FYI, you can download a working example from GitHub or check the Windows Forms online example.

Phone list c# (Reading from a file)

This is a pretty simple program. It IS a homework project. The program should start, read a .txt file, populate the name list and when you click on the name, the phone number is displayed. I have it coded, no errors, no warnings. It will not read the .txt file and I can't figure out why. I've been scouring my book, youtube, even here, but can't pin it down. Any help would be appreciated. Here is my current code.
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 Phonebook
{
struct PhoneBookEntry
{
public string name;
public string phone;
}
public partial class Form1 : Form
{
// FIeld to hold a list of PhoneBookEntry objects.
private List<PhoneBookEntry> phoneList = new List<PhoneBookEntry>();
public Form1()
{
InitializeComponent();
}
// The ReadFile method reads the contents of the
//PhoneList.txt file and tores it as PhoneBokeEntry
// objects in the phoneList.
private void ReadFile()
{
try
{
StreamReader inputFile; // To read the file
string line; // To hold a line from the file
// Create an instance of the PhoneBookEntry structure.
PhoneBookEntry entry = new PhoneBookEntry();
// Create a delimiter array.
char[] delim = { ',' };
// Open the PhoneList file.
inputFile = File.OpenText("PhoneList.txt");
// Read the lines from the file.
while (!inputFile.EndOfStream)
{
// Read a line from the file.
line = inputFile.ReadLine();
// Tokenize the line
string[] tokens = line.Split(delim);
// Store the tokens in the entry object.
entry.name = tokens[0];
entry.phone = tokens[1];
// Add the entry object to the List.
phoneList.Add(entry);
}
}
catch (Exception ex)
{
// Display an error message.
MessageBox.Show(ex.Message);
}
}
// The DisplayNames method displays the list of names
// in the namesListBox conrol.
private void DisplayNames()
{
foreach (PhoneBookEntry entry in phoneList)
{
nameListBox.Items.Add(entry.name);
}
}
private void Form1_Load(object sender, EventArgs e)
{
// Read the PhoneList.txt file.
ReadFile();
// DIsplay the names.
DisplayNames();
}
private void nameListBox_SelectedIndexChanged(object sender, EventArgs e)
{
// Get the index of the selected item.
int index = nameListBox.SelectedIndex;
// Display the corresponding phone number.
phoneLabel.Text = phoneList[index].phone;
}
private void exitButton_Click(object sender, EventArgs e)
{
// close the form.
this.Close();
}
private void Form1_Load_1(object sender, EventArgs e)
{
}
}
}

Using OpenFileDialog and StreamReader

There are two classes, one to cover the form (class 1) and the other to cover what gets displayed on the form (class 2). I'm trying to call a method in class 1 from class 2 to display certain information in a text box. I keep getting the error:
An object reference is required for the non-static field, method, or property
I've encountered this error before and been able to make it through, but nothing I've attempted so far has helped in this instance. I'm posting code for both the classes.
Class 1:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Forms;
namespace Project6
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void button1_Click(object sender, EventArgs e)
{
Stream myStream = null;
//Create an instance of the open file dialog box
OpenFileDialog ofd = new OpenFileDialog();
//Set parameters, filter options, and filter index
ofd.InitialDirectory = "c:\\";
ofd.Filter = "Text Files (.txt)|*.txt";
ofd.FilterIndex = 2;
ofd.Multiselect = false;
if (ofd.ShowDialog() == DialogResult.OK)
{
try
{
if ((myStream = ofd.OpenFile()) != null)
{
using (myStream = ofd.OpenFile())
{
StreamReader reader = new StreamReader(myStream);
string studentInformation = "";
string[] studentInformationArray = new string[11];
studentInformation = reader.ReadLine();
while ((studentInformation = reader.ReadLine()) != null)
{
studentInformationArray = studentInformation.Split(',');
Student newStudent = new Student(studentInformationArray);
}
}
}
}
catch (Exception ex)
{
MessageBox.Show("Error: Could not read file from disk. Original error: " + ex.Message);
}
}
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
textBox1.Text = Student.GetName(); //This generates the compiler error
textBox1.Select(6, 5);
MessageBox.Show(textBox1.SelectedText);
}
}
}
Class 2:
using System;
using System.Windows.Forms;
namespace Project6
{
class Student
{
//Initialize variables
private string[] studentInformationArray;
//Constructor that accepts the studentInformationArray as an argument
public Student(string[] studentInformationArray)
{
this.studentInformationArray = studentInformationArray;
}
public Student()
{
string className = studentInformationArray[1];
string semester = studentInformationArray[2];
string picture = studentInformationArray[3];
int project1 = Convert.ToInt32(studentInformationArray[4]);
int project2 = Convert.ToInt32(studentInformationArray[5]);
int project3 = Convert.ToInt32(studentInformationArray[6]);
int project4 = Convert.ToInt32(studentInformationArray[7]);
int project5 = Convert.ToInt32(studentInformationArray[8]);
int project6 = Convert.ToInt32(studentInformationArray[9]);
int midtermExam = Convert.ToInt32(studentInformationArray[10]);
int finalExam = Convert.ToInt32(studentInformationArray[11]);
}
public string GetName()
{
string studentName;
studentName = studentInformationArray[0];
return studentName;
}
}
}
That's because that's not how you use the OpenFileDialog. Take a look at this example hosted by the MSDN here:
Edit: answering to your edited question. You will always get a NullReferenceException in the Student() constructor because you are never assigning something to your studentInformationArray. So you can fix it like this:
public Student()
{
studentInformationArray = new studentInformationArray[12];
string className = studentInformationArray[1];
// rest of your code...
}
However, you should take into account that studentInformationArray will be an empty array unless you assign something to it. Since you have a Student() overload that takes a string[], I'd suggest you that you either remove the default constructor or make it call the overloaded with default information, like this:
public Student(string[] studentInformationArray)
{
string className = studentInformationArray[1];
// rest of your code...
int project1 = int.Parse(studentInformationArray[4]); // always prefer int.Parse() instead of Convert.ToInt32()
// rest of your code...
this.studentInformationArray = studentInformationArray;
}
public Student()
{
string[] defaultInformation = new string[12];
// add information
defaultInformation[0] = "some information";
// ...
new Student(defaultInformation);
}
Some more points to take into account:
Class-level fields/properties should be spelled in Pascal Case (first letter of each word in uppercase, rest in lowercase)
Try to never use this.variableName = variableName.
Variables names should never include the type of the variable, that's redundant.
So, for example, change this:
private string[] studentInformationArray;
for this:
private string[] StudentInformation;
Answering your last question, regarding the compiler error, you need a reference to the Student read in order to get its name. You could do something like this:
public partial class Form1 : Form
{
private Student StudentRead;
// rest of your code...
// from your read method:
StudentRead = new Student(studentInformationArray);
// and finally:
private void textBox1_TextChanged(object sender, EventArgs e)
{
textBox1.Text = StudentRead.GetName();

Using CodeDOM to source code and class file togther

i have created a form for a codeDOM compiler and it can compile my code if its in a single text file but i want to be able to compile the source code in the text file and a class thats in a text file so they can work together.
I am unsure how to code codeDOM to add my class file as a resource for the main source to be compiled
Heres what i have so far
codeDOM Compiler
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.CodeDom.Compiler;
using Microsoft.CSharp;
namespace CodeDOMSourceTest
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void btnCompile_Click(object sender, EventArgs e)
{
CompilerParameters Params = new CompilerParameters();
Params.GenerateExecutable = true;
Params.ReferencedAssemblies.Add("System.dll");
Params.ReferencedAssemblies.Add("TextFile1.txt");
Params.OutputAssembly = "output.exe";
string Source = Properties.Resources.CodeDOMSource;
Source = Source.Replace("[TEXT]", txtReplace.Text);
CompilerResults Results = new CSharpCodeProvider().CompileAssemblyFromSource(Params, Source);
if (Results.Errors.Count > 0)
{
foreach (CompilerError err in Results.Errors)
Console.WriteLine(err.ToString());
}
else Console.WriteLine("Compiled just fine!");
}
}
}
Source file
namespace testingCodeDOM
{
class Program
{
static void Main()
{
System.Console.WriteLine("[TEXT]");
Console.WriteLine(Testing.textwork());
System.Console.Read();
}
}
}
ClassFile
namespace testingCodeDOM
{
class Testing
{
public static string textwork()
{
string hello = "calss worked";
return hello;
}enter code here
}
}
Any ideas how to do this because i have googled it an am getting no were or at least nothing i understand
on a side not this works with with just the source but am trying to adapt it to use class files aswell
The CompileAssemblyFromSource() method can take any number of source code strings (since it's a params method). So, you can call it something like:
CompileAssemblyFromSource(Params, Source, ClassFile)
Where ClassFile is a string that contains the text of the second file.

Categories