Solved

streamwriter argumentexception in c#

Posted on 2011-03-22
9
613 Views
Last Modified: 2012-05-11
 Hi
I get a runtimeerror with the code below. I could probably solve the problem by not closing the first StreamWriter. Still curios why i get the error though.        

StreamWriter logWr2 = new StreamWriter(log);
            logWr2.WriteLine("Started connectToDatabase");
            logWr2.Close();
           
            StreamWriter logWr3 = new StreamWriter(log); //get argumentexception here
            logWr3.WriteLine("sqlCommand");
            logWr3.Close();
0
Comment
Question by:llegar100
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 3
  • 2
  • 2
  • +2
9 Comments
 
LVL 23

Expert Comment

by:wdosanjos
ID: 35191257
The code you posted works.  I think there is some code (not posted) between logWr2.Close() and StreamWriter logWr3 = new StreamWriter(log); that sets log to an invalid file name.

Check the ArgumentException Message for the error detail.
0
 
LVL 7

Expert Comment

by:jdavistx
ID: 35191675
Agreed, you should Debug to see what's going on with your log variable.

Also, when using objects that implement IDisposable, you should use the using block to properly close/dispose of the objects

StreamWriter logWriter2, logWriter3;
try
{
	using(logWriter2 = new StreamWriter(log), logWriter3 = new StreamWriter(log))
	{
		logWriter2.WriteLine("Started connectToDatabase");
		logWriter3.WriteLine("sqlCommand");
	}
}
catch(Exception e)
{
	//Exception handling
}
finally
{
	logWriter2.Close();
	logWriter3.Close();
}

Open in new window

0
 
LVL 14

Expert Comment

by:systan
ID: 35193066
Just following your code style;

            StreamWriter logWr2 = new StreamWriter(log);
            logWr2.WriteLine("Started connectToDatabase");

            logWr2.Dispose();
            logWr2.Close();
           
            StreamWriter logWr3 = new StreamWriter(log); //get argumentexception here
            logWr3.WriteLine("sqlCommand");

            logWr3.Dispose();
            logWr3.Close();
0
Salesforce Has Never Been Easier

Improve and reinforce salesforce training & adoption using WalkMe's digital adoption platform. Start saving on costly employee training by creating fast intuitive Walk-Thrus for Salesforce. Claim your Free Account Now

 

Author Comment

by:llegar100
ID: 35196313
Hi Thanks for your answers.
There is no code between logWr2.Close() and StreamWriter logWr3 = new StreamWriter(log


This is the error message:

System.ArgumentException was unhandled
  Message="Det gick inte att skriva till strömmen."
  Source="mscorlib"
  StackTrace:
       vid System.IO.StreamWriter..ctor(Stream stream, Encoding encoding, Int32 bufferSize)
       vid System.IO.StreamWriter..ctor(Stream stream)
       vid ConsoleApplication1.Program.connectToDatabase() i C:\ConsoleApplication3\Program.cs:rad 476
       vid ConsoleApplication1.Program.Main(String[] args) i C:\ConsoleApplication3\Program.cs:rad 40
       vid System.AppDomain._nExecuteAssembly(Assembly assembly, String[] args)
       vid System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args)
       vid Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
       vid System.Threading.ThreadHelper.ThreadStart_Context(Object state)
       vid System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
       vid System.Threading.ThreadHelper.ThreadStart()
  InnerException:

Doing this below I get the same error:
StreamWriter logWr2 = new StreamWriter(log);
            logWr2.WriteLine("Started connectToDatabase");

            logWr2.Dispose();
            logWr2.Close();
           
            StreamWriter logWr3 = new StreamWriter(log); //get argumentexception here
            logWr3.WriteLine("sqlCommand");

            logWr3.Dispose();
            logWr3.Close();
0
 

Accepted Solution

by:
llegar100 earned 0 total points
ID: 35196373
It works if i change the original line2 into line 1:

1: string log = "C:\\testing.txt"; //working
2: FileStream log = new FileStream("C:\\testing.txt", FileMode.Append, FileAccess.Write); //not working

Sorry if this is some basic thing, I am new to programming.
0
 
LVL 23

Expert Comment

by:wdosanjos
ID: 35198949
Got it.  I though log was a string, but it is a FileStream.  In that case when logWr2.Close(); is executed the log FileStream is closed also, so when you try to use it again it fails.  You need to recreate the log stream in this situation.  Something like this:

FileStream log = new FileStream("C:\\testing.txt", FileMode.Append, FileAccess.Write);
StreamWriter logWr2 = new StreamWriter(log);
logWr2.WriteLine("Started connectToDatabase");
logWr2.Close();

log = new FileStream("C:\\testing.txt", FileMode.Append, FileAccess.Write);
StreamWriter logWr3 = new StreamWriter(log);
logWr3.WriteLine("sqlCommand");
logWr3.Close();

Open in new window

0
 
LVL 15

Expert Comment

by:Russell_Venable
ID: 35202295
I am sorry to butt in on this but you should be calling this from a custom method like so.

1. This will make your code shorter.

2. This will clean up using GC correctly. Closing all streams in a safe way.

3. Its just easier to read ;) less frustration in the long run.



using System;
using System.IO;

class testlog
{
    static void Main()
    {
        srWriteLog(@"C:\test.txt", "Hello there");
    }

    public static void srWriteLog(string File, string WriteThis)
    {
        using(FileStream log = new FileStream(File, FileMode.Append, FileAccess.Write))
        using(StreamWriter srLog = new StreamWriter(log))
        {
            srLog.WriteLine(WriteThis);
            // These are not needed
            //log.Dispose();
            //log.Close();
            //srLog.Dispose():
            //srLog.Close();
        }
    }
}

Open in new window


This is tested and approved way of carrying this out. You cant go wrong.  Any exceptions after using this code from here on is user generated errors and not this method.
0
 
LVL 15

Expert Comment

by:Russell_Venable
ID: 35354370
Can you atleast post your solution as I did post the correct way to use streams. If it is in a seperate method like above not only will it be less code, but you not jave the errors you had in the first place. Along with the rest of who have contributed we would like to see how you fixed your problem if you don't mind.
0
 

Author Closing Comment

by:llegar100
ID: 35381851
solved it myself. Thanks for your comments.
0

Featured Post

[Live Webinar] The Cloud Skills Gap

As Cloud technologies come of age, business leaders grapple with the impact it has on their team's skills and the gap associated with the use of a cloud platform.

Join experts from 451 Research and Concerto Cloud Services on July 27th where we will examine fact and fiction.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Article by: Ivo
C# And Nullable Types Since 2.0 C# has Nullable(T) Generic Structure. The idea behind is to allow value type objects to have null values just like reference types have. This concerns scenarios where not all data sources have values (like a databa…
It was really hard time for me to get the understanding of Delegates in C#. I went through many websites and articles but I found them very clumsy. After going through those sites, I noted down the points in a easy way so here I am sharing that unde…
There's a multitude of different network monitoring solutions out there, and you're probably wondering what makes NetCrunch so special. It's completely agentless, but does let you create an agent, if you desire. It offers powerful scalability …
Monitoring a network: why having a policy is the best policy? Michael Kulchisky, MCSE, MCSA, MCP, VTSP, VSP, CCSP outlines the enormous benefits of having a policy-based approach when monitoring medium and large networks. Software utilized in this v…

626 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question