Solved

streamwriter argumentexception in c#

Posted on 2011-03-22
9
575 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
  • 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
 

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
Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

 

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

Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

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…
Exception Handling is in the core of any application that is able to dignify its name. In this article, I'll guide you through the process of writing a DRY (Don't Repeat Yourself) Exception Handling mechanism, using Aspect Oriented Programming.
This Micro Tutorial hows how you can integrate  Mac OSX to a Windows Active Directory Domain. Apple has made it easy to allow users to bind their macs to a windows domain with relative ease. The following video show how to bind OSX Mavericks to …
Learn how to create flexible layouts using relative units in CSS.  New relative units added in CSS3 include vw(viewports width), vh(viewports height), vmin(minimum of viewports height and width), and vmax (maximum of viewports height and width).

920 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

Need Help in Real-Time?

Connect with top rated Experts

16 Experts available now in Live!

Get 1:1 Help Now