Write to a file in a subroutine

Hi All,

I have a file that I created with StreamWriter in m Main function. I am able to to a WriteLine just fine on that.

However, I want to write to that same file from within the subroutine when I call it from the Main.

How can I do that?

For instance, I have something like this:

static void Main...
{
System.IO.StreamWriter filetest;
filetest = new System.IO.StreamWriter(@"D:\Testfile.txt");

{subroutine Test call}

filetest.WriteLine("Finished");

filetest.Close();
}

public static void Test()
{

       {do something...}

       {now I want to write to the file I created in the main like....}
       filetest.WriteLine("Procesing in subroutine");
}

How would/could I do something like that?
       

Any info would be greatly appreciated.

Thanks
LVL 1
davismAsked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

TomasPCommented:
Move the declaration of System.IO.StreamWriter filetest outside of main. Make it global or as one of the class members rather than a local. That way main opens it and other functions can use filetest as needed, then main can close filetest.
0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
wdosanjosCommented:
You can do something like this: (make filetest a static variable)

static System.IO.StreamWriter filetest;

static void Main...
{
filetest = new System.IO.StreamWriter(@"D:\Testfile.txt");

{subroutine Test call}

filetest.WriteLine("Finished");

filetest.Close();
}

public static void Test()
{

       {do something...}

       {now I want to write to the file I created in the main like....}
       filetest.WriteLine("Procesing in subroutine");
}

Open in new window

0
davismAuthor Commented:
You all beat me too it.

Complete brain fade on my part.

Thanks!
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
C#

From novice to tech pro — start learning today.

Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.