Solved

streamwriter argumentexception in c#

Posted on 2011-03-22
9
583 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
Courses: Start Training Online With Pros, Today

Brush up on the basics or master the advanced techniques required to earn essential industry certifications, with Courses. Enroll in a course and start learning today. Training topics range from Android App Dev to the Xen Virtualization Platform.

 

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

Courses: Start Training Online With Pros, Today

Brush up on the basics or master the advanced techniques required to earn essential industry certifications, with Courses. Enroll in a course and start learning today. Training topics range from Android App Dev to the Xen Virtualization Platform.

Question has a verified solution.

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

Suggested Solutions

Title # Comments Views Activity
Code works but it's slow 28 70
InputLanguage 1 25
HTML - Color not displaying correctly in EMAIL. 6 32
tableview is not updating 1 7
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…
Real-time is more about the business, not the technology. In day-to-day life, to make real-time decisions like buying or investing, business needs the latest information(e.g. Gold Rate/Stock Rate). Unlike traditional days, you need not wait for a fe…
Windows 10 is mostly good. However the one thing that annoys me is how many clicks you have to do to dial a VPN connection. You have to go to settings from the start menu, (2 clicks), Network and Internet (1 click), Click VPN (another click) then fi…
With Secure Portal Encryption, the recipient is sent a link to their email address directing them to the email laundry delivery page. From there, the recipient will be required to enter a user name and password to enter the page. Once the recipient …

785 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