james
james

Reputation: 21

C# not recognizing my variable

I'm trying to load code from an exe file then create it into a new .exe file. But it's not recognizing my variable "SourceCode". It says the name "SourceCode" does not exist in the current context

     private void button1_Click(object sender, EventArgs e)
    {

        using (FileStream SourceCode = new FileStream("thecode.exe", FileMode.Open, FileAccess.ReadWrite, FileShare.None));
        string Output = textBox3.Text;
        String[] Assembly = { "System.dll", "System.Drawing.dll", "System.Windows.Forms.dll" };
        CodeDomProvider CodeCompiler = CodeDomProvider.CreateProvider("CSharp");
        CompilerParameters Parameters = new CompilerParameters(Assembly, "");

        Parameters.OutputAssembly = Output;
        Parameters.GenerateExecutable = true;
        Parameters.GenerateInMemory = false;
        Parameters.WarningLevel = 3;
        Parameters.TreatWarningsAsErrors = true;
        Parameters.CompilerOptions = "/optimize+ /target:winexe";
        string Errors = null;
        try
        {
            CompilerResults Results = null;
            Results = CodeCompiler.CompileAssemblyFromSource(Parameters, SourceCode); //This here is giving me an error
            if (Results.Errors.Count > 0)
            {
                Errors = "";
                foreach (System.CodeDom.Compiler.CompilerError CompileError in Results.Errors)
                {
                    Errors += "Line number " + CompileError.Line + ", Error Number: " + CompileError.ErrorNumber + ", '" + CompileError.ErrorText + ";\r\n\r\n";
                }

Upvotes: 1

Views: 1316

Answers (2)

Helix 88
Helix 88

Reputation: 701

The following line is ending with a semicolon ';'

using (FileStream SourceCode = new FileStream("thecode.exe", FileMode.Open, FileAccess.ReadWrite, FileShare.None));

In C# the semicolon is a statement terminator rather than a line terminator. You should declare your using statements like this

using(var Bar = new Foo())
{
}

Thus making your code:

using (FileStream SourceCode = new FileStream("thecode.exe", FileMode.Open, FileAccess.ReadWrite, FileShare.None))
{
}

Upvotes: 8

Philippe Paré
Philippe Paré

Reputation: 4418

Your using statement at the top has a ; at the end. A using block is used to ensure a Disposable resource is disposed at the end of the block. In this case, without { }, your using statement is kind of useless. Either your expand the block of code using { }, or you just declare the variable without the using statement. Hope this helps!

Upvotes: 3

Related Questions