MainDQMClass.ListFiles(@"C:\Windows");
Non static members can ONLY be accessed via an object (instantiated class) as in:MainDQMClass mdqmc = new MainDQMClass(); mdqmc.Connection = new SQLConnection();If you want to stick with static methods, you'll either want to create and destroy the connection within each method (which I suspect you don't want to do), or add a connection parameter to all the static methods, create it in your calling code and pass it to each static method. Alternatively, you could make all your methods not static and just instantiate the class and it should run fine (which is maybe what your original intent was anyway).
>using System; >using System.IO; >using System.Data; >using System.Data.SqlClient; >using System.Data.SqlTypes; >namespace ConsoleSample >{ > class MainDQMClass > { > public const string INPUTFOLDER = @"c:\temp\"; > > // here's the one I want to define globally to be reused > // but I can't get to work. Is this the correct way? > public SqlConnection oConnection; > > [STAThread] > public static int Main(string[] args) > { > int nReturnCode = 0; > > // global error handler > try > { > // reads input folder (dir) > // process each file found > ListFiles(INPUTFOLDER); > } > catch (Exception e) > { > nReturnCode = -1; > // call a method to log error > } > return nReturnCode; > } > > public static void ListFiles(string cFolder) > { > DirectoryInfo dir = new DirectoryInfo(cFolder); > foreach (FileInfo f in dir.GetFiles("*.txt")) > { > // for test purposes, list filename to console > Console.Write(f.FullName+"\n"); > > // process each file > bool lWasProcessed=ProcessInput(f); > > // move processed file to archive folder > if (lWasProcessed) > { > MoveToArchive(f); > } > } > } > > public static bool ProcessInput(FileInfo f) > { > bool lError=false; > > // create a connection, keep open while processing batch > try > { > oConnection = ConnectToSqlServer(); > } > catch (Exception oErr) > { > lError=true; > // log error > } > > // if connection is open here is where we do the whole > // data processing... > // oConnection is used extensively in the many methods that follow (not shown) > // all fail to compile as oConnection sems to be out of scope > } > > public static SqlConnection ConnectToSqlServer() > { > string cUID="test"; > string cPWD="PASSWORD"; > > // Create the connection > SqlConnection conn = new SqlConnection(); > conn.ConnectionString = "server=xxxx;"+ > "uid="+cUID+ > ";pwd="+cPWD+ > ";database=DataQuality"; > > try > { > conn.Open(); > } > catch (Exception oErr) > { > //"Failed to connect to data source.\n"+oErr.Message > } > return conn; > } > } >} >>
>An object reference is required for the nonstatic field, method or property 'xxx' >>This happens on every method that uses the connection. What am I missing that is so basic as scope?