Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Error: A namespace cannot directly contain members such as fields or methods [duplicate]

Tags:

c#

I'm new to C# and I'm having trouble solving this error can anyone help me please? This script is to delete an un-needed shortcut then install a new program if it hasn't been installed already.

using System;
using WindowsInstaller;


string startMenuDir = Environment.GetFolderPath(Environment.SpecialFolder.StartMenu);
string shortcutold = Path.Combine(startMenuDir, @"Ohal\TV AMP (Windows XP Mode).lnk");
if (File.Exists(shortcutold))
File.Delete(shortcutold);


string startMenuDir = Environment.GetFolderPath(Environment.SpecialFolder.StartMenu);
string shortcut = Path.Combine(startMenuDir, @"Ohal\TV AMP.lnk");
if (File.Exists(shortcut))
{
    Console.WriteLine("Already installed...");
}
else
{
Type type = Type.GetTypeFromProgID("WindowsInstaller.Installer");
            Installer installer = (Installer)Activator.CreateInstance(type);
            installer.InstallProduct(@"Y:\LibSetup\TVAMP313\TVAmp v3.13.msi");
}
like image 538
user1823287 Avatar asked Nov 14 '12 09:11

user1823287


People also ask

What does error CS0116 mean?

error CS0116: A namespace cannot directly contain members such as fields or methods- hand writing coding using notepad.

What is a namespace in C#?

The namespace keyword is used to declare a scope that contains a set of related objects. You can use a namespace to organize code elements and to create globally unique types. C# Copy.


2 Answers

Your code should be in a class and then a method. You can't have code under namespace. Something like following.

using System;
using WindowsInstaller;

class MyClass //Notice the class 
{
 //You can have fields and properties here

    public void MyMethod() // then the code in a method
    {
        string startMenuDir = Environment.GetFolderPath(Environment.SpecialFolder.StartMenu);
        string shortcutold = Path.Combine(startMenuDir, @"Ohal\TV AMP (Windows XP Mode).lnk");
        if (File.Exists(shortcutold))
            File.Delete(shortcutold);
       // your remaining code .........


    }
}
like image 74
Habib Avatar answered Oct 05 '22 22:10

Habib


As Habib says, you need to put code in methods, constructors etc. In this case if the code you want is just what you want as the entry point, you just need:

using System;
using WindowsInstaller;

class Program
{
    // Or static void Main(string[] args) to use command line arguments
    static void Main()
    {
        string startMenuDir = ...;
        string shortcutold = ...;
        // Rest of your code
    }
}

Basically the Main method is the entry point for a stand-alone C# program.

Of course, if your code is meant to be a plug-in for something else, you may need to just implement an interface or something similar. Either way, you'll have to have your code in members rather than just "bare".

like image 22
Jon Skeet Avatar answered Oct 06 '22 00:10

Jon Skeet