0

I have below code with error. Error message is very simple but I cant get its sense. To me looks like fileStream is being initalized when it is reading data. Can you please guide what I m missing ?

  class Program
{        
    Stream fileStream=null;       

    static void Main(string[] args)
    {
    }

    private static void ReadData()
    {      


        using (System.Net.WebResponse tmpRes = ftpReq.GetResponse())
        {
             fileStream = tmpRes.GetResponseStream();                
        }
    }

EDIT: I have simplified this code and removed few parts. Error is on fileStream = tmpRes.GetResponseStream();

Babak Naffas
  • 12,395
  • 3
  • 34
  • 49
user576510
  • 5,777
  • 20
  • 81
  • 144
  • 1
    Change it to `static Stream fileStream = null`, you are missing the `static` identifier. – Ron Beyer Feb 25 '18 at 23:16
  • 1
    Possible duplicate of [CS0120: An object reference is required for the nonstatic field, method, or property 'foo'](https://stackoverflow.com/questions/498400/cs0120-an-object-reference-is-required-for-the-nonstatic-field-method-or-prop) – TnTinMn Feb 25 '18 at 23:19
  • 1
    The answer is very simple: if you are in a static method or a static class, you can only use other static "things". Therefore, `fileStream` needs to be static. – CodingYoshi Feb 25 '18 at 23:36

1 Answers1

3

You are referencing a member variable within a static method. A member variable requires an instance of the class to be referenced where as a static method does not and can be shared across instances of the class.

Change Stream fileStream=null; to static Stream fileStream=null;

Babak Naffas
  • 12,395
  • 3
  • 34
  • 49
  • Thanks Babak. I changed ReadData() method to non static. That issue was resolved. I tried calling ReadData() into Main() and same error was coming on calling ReadData(). Can you please suggest what change I should do ? Thanks for this. – user576510 Feb 25 '18 at 23:22
  • 1
    `static void Main(string[] args)` is the entry point into your application, so that must remain static. An option would be to move the code for reading from the FTP server to its own class. You can then create an instance of that class and call ReadData on that instance. – Babak Naffas Feb 25 '18 at 23:24
  • @user576510 when you changed `ReadData` to non static, you solved the previous issue but created the exact same issue again elsewhere. Now since `Main` method is `static`, you cannot call the non static method `ReadData` from it. Same issue as before but elsewhere im code. You need to read and study `static`. Dont keep trying things until something works. Know why it works and why it does not work. – CodingYoshi Feb 25 '18 at 23:42