Still celebrating National IT Professionals Day with 3 months of free Premium Membership. Use Code ITDAY17

x
?
Solved

streamwriter argumentexception in c#

Posted on 2011-03-22
9
Medium Priority
?
623 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
Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 

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

Free Tool: Site Down Detector

Helpful to verify reports of your own downtime, or to double check a downed website you are trying to access.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Question has a verified solution.

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

Calculating holidays and working days is a function that is often needed yet it is not one found within the Framework. This article presents one approach to building a working-day calculator for use in .NET.
This article aims to explain the working of CircularLogArchiver. This tool was designed to solve the buildup of log file in cases where systems do not support circular logging or where circular logging is not enabled
Do you want to know how to make a graph with Microsoft Access? First, create a query with the data for the chart. Then make a blank form and add a chart control. This video also shows how to change what data is displayed on the graph as well as form…
In this video, Percona Director of Solution Engineering Jon Tobin discusses the function and features of Percona Server for MongoDB. How Percona can help Percona can help you determine if Percona Server for MongoDB is the right solution for …

704 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