Solved

streamwriter argumentexception in c#

Posted on 2011-03-22
9
565 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
What Is Threat Intelligence?

Threat intelligence is often discussed, but rarely understood. Starting with a precise definition, along with clear business goals, is essential.

 

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

Threat Intelligence Starter Resources

Integrating threat intelligence can be challenging, and not all companies are ready. These resources can help you build awareness and prepare for defense.

Join & Write a Comment

Introduction                                                 Was the var keyword really only brought out to shorten your syntax? Or have the VB language guys got their way in C#? What type of variable is it? All will be revealed.   Also called…
Introduction This article series is supposed to shed some light on the use of IDisposable and objects that inherit from it. In essence, a more apt title for this article would be: using (IDisposable) {}. I’m just not sure how many people would ge…
In this seventh video of the Xpdf series, we discuss and demonstrate the PDFfonts utility, which lists all the fonts used in a PDF file. It does this via a command line interface, making it suitable for use in programs, scripts, batch files — any pl…
In this tutorial you'll learn about bandwidth monitoring with flows and packet sniffing with our network monitoring solution PRTG Network Monitor (https://www.paessler.com/prtg). If you're interested in additional methods for monitoring bandwidt…

746 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

12 Experts available now in Live!

Get 1:1 Help Now