Search Results

Search found 265 results on 11 pages for 'streamwriter'.

Page 1/11 | 1 2 3 4 5 6 7 8 9 10 11  | Next Page >

  • StreamWriter appends random data

    - by void
    Hi I'm seeing odd behaviour using the StreamWriter class writing extra data to a file using this code: public void WriteToCSV(string filename) { StreamWriter streamWriter = null; try { streamWriter = new StreamWriter(filename); Log.Info("Writing CSV report header information ... "); streamWriter.WriteLine("\"{0}\",\"{1}\",\"{2}\",\"{3}\"", ((int)CSVRecordType.Header).ToString("D2", CultureInfo.CurrentCulture), m_InputFilename, m_LoadStartDate, m_LoadEndDate); int recordCount = 0; if (SummarySection) { Log.Info("Writing CSV report summary section ... "); foreach (KeyValuePair<KeyValuePair<LoadStatus, string>, CategoryResult> categoryResult in m_DataLoadResult.DataLoadResults) { streamWriter.WriteLine("\"{0}\",\"{1}\",\"{2}\",\"{3}\"", ((int)CSVRecordType.Summary).ToString("D2", CultureInfo.CurrentCulture), categoryResult.Value.StatusString, categoryResult.Value.Count.ToString(CultureInfo.CurrentCulture), categoryResult.Value.Category); recordCount++; } } Log.Info("Writing CSV report cases section ... "); foreach (KeyValuePair<KeyValuePair<LoadStatus, string>, CategoryResult> categoryResult in m_DataLoadResult.DataLoadResults) { foreach (CaseLoadResult result in categoryResult.Value.CaseLoadResults) { if ((LoadStatus.Success == result.Status && SuccessCases) || (LoadStatus.Warnings == result.Status && WarningCases) || (LoadStatus.Failure == result.Status && FailureCases) || (LoadStatus.NotProcessed == result.Status && NotProcessedCases)) { streamWriter.Write("\"{0}\",\"{1}\",\"{2}\",\"{3}\",\"{4}\"", ((int)CSVRecordType.Result).ToString("D2", CultureInfo.CurrentCulture), result.Status, result.UniqueId, result.Category, result.ClassicReference); if (RawResponse) { streamWriter.Write(",\"{0}\"", result.ResponseXml); } streamWriter.WriteLine(); recordCount++; } } } streamWriter.WriteLine("\"{0}\",\"{1}\"", ((int)CSVRecordType.Count).ToString("D2", CultureInfo.CurrentCulture), recordCount); Log.Info("CSV report written to '{0}'", fileName); } catch (IOException execption) { string errorMessage = string.Format(CultureInfo.CurrentCulture, "Unable to write XML report to '{0}'", fileName); Log.Error(errorMessage); Log.Error(exception.Message); throw new MyException(errorMessage, exception); } finally { if (null != streamWriter) { streamWriter.Close(); } } } The file produced contains a set of records on each line 0 to N, for example: [Record Zero] [Record One] ... [Record N] However the file produced either contains nulls or incomplete records from further up the file appended to the end. For example: [Record Zero] [Record One] ... [Record N] [Lots of nulls] or [Record Zero] [Record One] ... [Record N] [Half complete records] This also happens in separate pieces of code that also use the StreamWriter class. Furthermore, the files produced all have sizes that are multiples of 1024. I've been unable to reproduce this behaviour on any other machine and have tried recreating the environment. Previous versions of the application didn't exhibite this behaviour despite having the same code for the methods in question. EDIT: Added extra code.

    Read the article

  • StreamWriter not creating new file

    - by fearofawhackplanet
    I'm trying to create a new log file every hour with the following code running on a server. The first log file of the day is being created and written to fine, but no further log files that day get created. Any ideas what might be going wrong? No exceptions are thrown either. private void LogMessage(Message msg) { using (StreamWriter sw = File.AppendText(_logDirectory + DateTime.Today.ToString("yyyyMMddHH") + ".txt")) { sw.WriteLine(msg.ToString()); } }

    Read the article

  • StreamWriter stops writing when file is opened from web link

    - by fearofawhackplanet
    Following on from my previous question... The following code creates log files on a web server: private void LogMessage(Message msg) { using (StreamWriter sw = File.AppendText(_logDirectory + DateTime.Now.ToString("yyyyMMddHH") + ".txt")) { sw.WriteLine(msg.ToString()); } } The log files are linked to from an admin page on the web site: foreach (FileInfo file in logDir.GetFiles()) { Response.Write("<a href='http:// .... /Logs/" + file.Name + "'>" + file.Name + "</a>"); } I'm getting the problem that after someone looks at one of the log files from the link, that log file stops being written to.

    Read the article

  • What is the difference between calling Stream.Write and using a StreamWriter?

    - by John Nelson
    What is the difference between instantiating a Stream object, such as MemoryStream and calling the memoryStream.Write() method to write to the stream, and instantiating a StreamWriter object with the stream and calling streamWriter.Write()? Consider the following scenario: You have a method that takes a Stream, writes a value, and returns it. The stream is read from later on, so the position must be reset. There are two possible ways of doing it (both seem to work). // Instantiate a MemoryStream somewhere // - Passed to the following two methods MemoryStream memoryStream = new MemoryStream(); // Not using a StreamWriter private static Stream WriteToStream(Stream stream, string value) { stream.Write(Encoding.Default.GetBytes(value), 0, value.Length); stream.Flush(); stream.Position = 0; return stream; } // Using a StreamWriter private static Stream WriteToStreamWithWriter(Stream stream, string value) { StreamWriter sw = new StreamWriter(stream); sw.Write(value, 0, value.Length); sw.Flush(); stream.Position = 0; return stream; } This is partially a scope problem, as I don't want to close the stream after writing to it since it will be read from later. I also certainly don't want to dispose it either, because that will close my stream. The difference seems to be that not using a StreamWriter introduces a direct dependency on Encoding.Default, but I'm not sure that's a very big deal. What's the difference, if any?

    Read the article

  • How do I write escape characters verbatim (without escaping) in C# using StreamWriter?

    - by Joel
    I'm writing a utility that takes in a .resx file and creates a javascript object containing properties for all the name/value pairs in the .resx file. This is all well and good, until one of the values in the .resx is This dealer accepts electronic orders. /r/nClick to order {0} from this dealer. I'm adding the name/value pairs to the js object like this: streamWriter.Write(string.Format("\n{0} : \"{1}\"", kvp.Key, kvp.Value)); When kvp.Value = "This dealer accepts electronic orders./r/nClick to order {0} from this dealer." This causes StreamWriter.Write() to actually place a newline in between 'orders.' and 'Click', which naturally screws up my javascript output. I've tried different things with @ and without using string.Format, but I've had no luck. Any suggestions?

    Read the article

  • StreamWriter does throw exception underlying connection is broken?

    - by Jane
    I am using StreamWriter instantiated over a Tcpstream like this streamWriter = new StreamWriter(tcpClient.GetStream()); I am confused about the behaviour of following calls with regards to Exceptions. The following two functions are expected to raise IOException , Surprisingly they do not raise the IOException when the server is to which the tcpClient is connected is disconnected and therefore the underlying TCP client connection is broken.. These two lines execute without raising any Exception. Why ? streamWriter.WriteLine(strBuffer); streamWriter.Flush();

    Read the article

  • How do I write escape characters verbatim (without escaping) using StreamWriter?

    - by Joel
    I'm writing a utility that takes in a .resx file and creates a javascript object containing properties for all the name/value pairs in the .resx file. This is all well and good, until one of the values in the .resx is This dealer accepts electronic orders. /r/nClick to order {0} from this dealer. I'm adding the name/value pairs to the js object like this: streamWriter.Write(string.Format("\n{0} : \"{1}\"", kvp.Key, kvp.Value)); When kvp.Value = "This dealer accepts electronic orders./r/nClick to order {0} from this dealer." This causes StreamWriter.Write() to actually place a newline in between 'orders.' and 'Click', which naturally screws up my javascript output. I've tried different things with @ and without using string.Format, but I've had no luck. Any suggestions? Edit: This application is run during build to get some javascript files deployed later, so at no point is it accessible to / run by anyone but the app developers. So while I obviously need a way to escape characters here, XSS as such is not really a concern.

    Read the article

  • Saving to a file in C# [on hold]

    - by user36322
    If I use this code: using (StreamWriter streamWriter = new StreamWriter("Content/player.txt", true)) { streamWriter.Write("Hello!"); streamWriter.Close(); } The program will not actually add "Hello!" to the file. However, if I use this code: using (StreamWriter streamWriter = new StreamWriter("C:/Users/Michael/Documents/Visual Studio 2010/Projects/PuzzleGame/PuzzleGame/PuzzleGameContent/player.TXT", true)) { streamWriter.Write("Hello!"); streamWriter.Close(); } The program will work as intended and add "Hello!" to the save file. Is there any way I can do this without hardcoding the path?

    Read the article

  • Reading a POP3 server with only TcpClient and StreamWriter/StreamReader[SOLVED]

    - by WebDevHobo
    I'm trying to read mails from my live.com account, via the POP3 protocol. I've found the the server is pop3.live.com and the port if 995. I'm not planning on using a pre-made library, I'm using NetworkStream and StreamReader/StreamWriter for the job. I need to figure this out. So, any of the answers given here: http://stackoverflow.com/questions/44383/reading-email-using-pop3-in-c are not usefull. It's part of a larger program, but I made a small test to see if it works. Eitherway, i'm not getting anything. Here's the code I'm using, which I think should be correct. EDIT: this code is old, please refer to the second block problem solved. public Program() { string temp = ""; using(TcpClient tc = new TcpClient(new IPEndPoint(IPAddress.Parse("127.0.0.1"),8000))) { tc.Connect("pop3.live.com",995); using(NetworkStream nws = tc.GetStream()) { using(StreamReader sr = new StreamReader(nws)) { using(StreamWriter sw = new StreamWriter(nws)) { sw.WriteLine("USER " + user); sw.Flush(); sw.WriteLine("PASS " + pass); sw.Flush(); sw.WriteLine("LIST"); sw.Flush(); while(temp != ".") { temp += sr.ReadLine(); } } } } } Console.WriteLine(temp); } Visual Studio debugger constantly falls over tc.Connect("pop3.live.com",995); Which throws an "A socket operation was attempted to an unreachable network 65.55.172.253:995" error. So, I'm sending from port 8000 on my machine to port 995, the hotmail pop3 port. And I'm getting nothing, and I'm out of ideas. Second block: Problem was apparently that I didn't write the quit command. The Code: public Program() { string str = string.Empty; string strTemp = string.Empty; using(TcpClient tc = new TcpClient()) { tc.Connect("pop3.live.com",995); using(SslStream sl = new SslStream(tc.GetStream())) { sl.AuthenticateAsClient("pop3.live.com"); using(StreamReader sr = new StreamReader(sl)) { using(StreamWriter sw = new StreamWriter(sl)) { sw.WriteLine("USER " + user); sw.Flush(); sw.WriteLine("PASS " + pass); sw.Flush(); sw.WriteLine("LIST"); sw.Flush(); sw.WriteLine("QUIT "); sw.Flush(); while((strTemp = sr.ReadLine()) != null) { if(strTemp == "." || strTemp.IndexOf("-ERR") != -1) { break; } str += strTemp; } } } } } Console.WriteLine(str); }

    Read the article

  • Rapid Opening and Closing System.IO.StreamWriter in C#

    - by ccomet
    Suppose you have a file that you are programmatically logging information into with regards to a process. Kinda like your typical debug Console.WriteLine, but due to the nature of the code you're testing, you don't have a console to write onto so you have to write it somewhere like a file. My current program uses System.IO.StreamWriter for this task. My question is about the approach to using the StreamWriter. Is it better to open just one StreamWriter instance, do all of the writes, and close it when the entire process is done? Or is it a better idea to open a new StreamWriter instance to write a line into the file, then immediately close it, and do this for every time something needs to be written in? In the latter approach, this would probably be facilitated by a method that would do just that for a given message, rather than bloating the main process code with excessive amounts of lines. But having a method to aid in that implementation doesn't necessarily make it the better choice. Are there significant advantages to picking one approach or the other? Or are they functionally equivalent, leaving the choice on the shoulders of the programmer?

    Read the article

  • Program crashes after trying to use a recently created file. C#

    - by Jason T.
    So here is my code if (!File.Exists(pathName)) { File.Create(pathName); } StreamWriter outputFile = new StreamWriter(pathName,true); But whenever I run the program the first time the path with file gets created. However once I get to the StreamWriter line my program crashes because it says my fie is in use by another process. Is there something I'm missing between the File.Create and the StreamWriter statements?

    Read the article

  • Reading a POP3 server with only TcpClient and StreamWriter/StreamReader

    - by WebDevHobo
    I'm trying to read mails from my live.com account, via the POP3 protocol. I've found the the server is pop3.live.com and the port if 587. I'm not planning on using a pre-made library, I'm using NetworkStream and StreamReader/StreamWriter for the job. I need to figure this out. So, any of the answers given here: http://stackoverflow.com/questions/44383/reading-email-using-pop3-in-c are not usefull. It's part of a larger program, but I made a small test to see if it works. Eitherway, i'm not getting anything. Here's the code I'm using, which I think should be correct. public Program() { string temp = ""; using(TcpClient tc = new TcpClient(new IPEndPoint(IPAddress.Parse("127.0.0.1"),8000))) { tc.Connect("pop3.live.com",587); using(NetworkStream nws = tc.GetStream()) { using(StreamReader sr = new StreamReader(nws)) { using(StreamWriter sw = new StreamWriter(nws)) { sw.WriteLine("USER " + user); sw.Flush(); sw.WriteLine("PASS " + pass); sw.Flush(); sw.WriteLine("LIST"); sw.Flush(); while(temp != ".") { temp += sr.ReadLine(); } } } } } Console.WriteLine(temp); } So, I'm sending from port 8000 on my machine to port 587, the hotmail pop3 port. And I'm getting nothing, and I'm out of ideas.

    Read the article

  • Using A Local file path in a Streamwriter object ASP.Net

    - by Nick LaMarca
    I am trying to create a csv file of some data. I have wrote a function that successfully does this.... Private Sub CreateCSVFile(ByVal dt As DataTable, ByVal strFilePath As String) Dim sw As New StreamWriter(strFilePath, False) ''# First we will write the headers. ''EDataTable dt = m_dsProducts.Tables[0]; Dim iColCount As Integer = dt.Columns.Count For i As Integer = 0 To iColCount - 1 sw.Write(dt.Columns(i)) If i < iColCount - 1 Then sw.Write(",") End If Next sw.Write(sw.NewLine) ''# Now write all the rows. For Each dr As DataRow In dt.Rows For i As Integer = 0 To iColCount - 1 If Not Convert.IsDBNull(dr(i)) Then sw.Write(dr(i).ToString()) End If If i < iColCount - 1 Then sw.Write(",") End If Next sw.Write(sw.NewLine) Next sw.Close() End Sub The problem is I am not using the streamwriter object correctly for what I trying to accomplish. Since this is an asp.net I need the user to pick a local filepath to put the file on. If I pass any path to this function its gonna try to write it to the directory specified on the server where the code is. I would like this to popup and let the user select a place on their local machine to put the file.... Dim exData As Byte() = File.ReadAllBytes(Server.MapPath(eio)) File.Delete(Server.MapPath(eio)) Response.AddHeader("content-disposition", String.Format("attachment; filename={0}", fn)) Response.ContentType = "application/x-msexcel" Response.BinaryWrite(exData) Response.Flush() Response.End() I am calling the first function in code like this... Dim emplTable As DataTable = SiteAccess.DownloadEmployee_H() CreateCSVFile(emplTable, "C:\\EmplTable.csv") Where I dont want to have specify the file loaction (because this will put the file on the server and not on a client machine) but rather let the user select the location on their client machine. Can someone help me put this together? Thanks in advance.

    Read the article

  • Writing a file by a webservice

    - by mouthpiec
    Hi, I have a wevservice, and I would like to write logs into a textfile. My problem is that i do not know what path to give when creating the streamwriter: TextWriter tw = new StreamWriter("????"); Can you please help what path I should enter?

    Read the article

  • StreamWriter Problem - 2 Spaces Written as Hex '20 c2 a0' instead of Hex '20 20'

    - by Daver
    I'm writing a bunch of strings to a file using a string writer but I've discovered a problem when I look at the file created in hex, and that is that one of the spaces (x20) is replaced with a non-breaking space instead (xc2 a0) when there are 2 spaces separating words. I don't know if this is a big deal but I would like to know if there is an easy resolution to this? Here's what I'm seeing: 20 c2 a0 53 57 45 45 50 Dump = "  SWEEP" But I would like it to always be: 20 20 53 57 45 45 50 Dump = " SWEEP" Note that the c2 a0 aren't visible here but the dump looks something like 'A.' when I use the Notepad++ Hex Plugin. Does anyone have any ideas? Cheers and Thanks In Advance; -Daver

    Read the article

  • Exporting winform data to .txt file

    - by EvanRyan
    I have a winform with two data grids, and multiple text boxes. I want to give the user the option to export this data to a text document in a location of their choice on their drive. I also want the text document to be pre-formatted, and the values from the text boxes and datagrids to be plugged in. Is it possible to pre-format a txt document using StreamWriter? And how to I go about giving the user the option of where to save this exported file?

    Read the article

  • Problem while configuring the file Delimeter("\t") in app.config(C#3.0)

    - by Newbie
    In my app.config file I made the setting like the following <add key = "Delimeter" value ="\t"/> Now while accessing the above from the program by using the below code string delimeter = ConfigurationManager.AppSettings["FileDelimeter"].ToString(); StreamWriter streamWriter = null; streamWriter = new StreamWriter(fs); streamWriter.BaseStream.Seek(0, SeekOrigin.End); Enumerable .Range(0, outData.Length) .ToList().ForEach(i => streamWriter.Write(outData[i].ToString() + delimiter)); streamWriter.WriteLine(); streamWriter.Flush(); I am getting the output as 18804\t20100326\t5.59975381254617\t 18804\t20100326\t1.82599797249479\t But if I directly use "\t" in the delimeter variable I am getting the correct output 18804 20100326 5.59975381254617 18804 20100326 1.82599797249479 I found that while I am specifying the "\t" in the config file, and while reading it into the delimeter variable, it is becoming "\\t" which is the problem. I even tried with but with no luck. I am using C#3.0. Need help

    Read the article

  • Reading column header and column values of a data table using LAMBDA(C#3.0)

    - by Newbie
    Consider the folowing where I am reading the data table values and writing to a text file using (StreamWriter sw = new StreamWriter(@"C:\testwrite.txt",true)) { DataPreparation().AsEnumerable().ToList().ForEach(i => { string col1 = i[0].ToString(); string col2 = i[1].ToString(); string col3 = i[2].ToString(); string col4 = i[3].ToString(); sw.WriteLine( col1 + "\t" + col2 + "\t" + col3 + "\t" + col4 + Environment.NewLine ); }); } The data preparation function is as under private static DataTable DataPreparation() { DataTable dt = new DataTable(); dt.Columns.Add("Col1", typeof(string)); dt.Columns.Add("Col2", typeof(int)); dt.Columns.Add("Col3", typeof(DateTime)); dt.Columns.Add("Col4", typeof(bool)); for (int i = 0; i < 10; i++) { dt.Rows.Add("String" + i.ToString(), i, DateTime.Now.Date, (i % 2 == 0) ? true : false); } return dt; } It is working fine. Now in the above described program, it is known to me the Number of columns and the column headers. How to achieve the same in case when the column headers and number of columns are not known at compile time using the lambda expression? I have already done that which is as under public static void WriteToTxt(string directory, string FileName, DataTable outData, string delimiter) { FileStream fs = null; StreamWriter streamWriter = null; using (fs = new FileStream(directory + "\\" + FileName + ".txt", FileMode.Append, FileAccess.Write)) { try { streamWriter = new StreamWriter(fs); streamWriter.BaseStream.Seek(0, SeekOrigin.End); streamWriter.WriteLine(); DataTableReader datatableReader = outData.CreateDataReader(); for (int header = 0; header < datatableReader.FieldCount; header++) { streamWriter.Write(outData.Columns[header].ToString() + delimiter); } streamWriter.WriteLine(); int row = 0; while (datatableReader.Read()) { for (int field = 0; field < datatableReader.FieldCount; field++) { streamWriter.Write(outData.Rows[row][field].ToString() + delimiter); } streamWriter.WriteLine(); row++; } } catch (Exception ex) { throw ex; } } } I am using C#3.0 and framework 3.5 Thanks in advance

    Read the article

  • Is there anyway to close a StreamWriter without closing it's BaseStream?

    - by Binary Worrier
    My root problem is that when using calls Dispose on a StreamWriter, it also disposes the BaseStream (same problem with Close). I have a workaround for this, but as you can see it involves copying the stream. Is there any way to do this without copying the stream? The purpose of this is to get the contents of a string (originally read from a database) into a stream, so the stream can be read by a third party component. NB I cannot change the third party component. public System.IO.Stream CreateStream(string value) { var baseStream = new System.IO.MemoryStream(); var baseCopy = new System.IO.MemoryStream(); using (var writer = new System.IO.StreamWriter(baseStream, System.Text.Encoding.UTF8)) { writer.Write(value); writer.Flush(); baseStream.WriteTo(baseCopy); } baseCopy.Seek(0, System.IO.SeekOrigin.Begin); return baseCopy; } Used as public void Noddy() { System.IO.Stream myStream = CreateStream("The contents of this string are unimportant"); My3rdPartyComponent.ReadFromStream(myStream); } Ideally I'm looking for an imaginery method called BreakAssociationWithBaseStream, e.g. public System.IO.Stream CreateStream_Alternate(string value) { var baseStream = new System.IO.MemoryStream(); using (var writer = new System.IO.StreamWriter(baseStream, System.Text.Encoding.UTF8)) { writer.Write(value); writer.Flush(); writer.BreakAssociationWithBaseStream(); } return baseStream; }

    Read the article

  • how to run line by line in text file - on windows mobile ?

    - by Gold
    hi in WinForm on PC i use to run like this: FileStream FS = null; StreamWriter SW = null; FS = new FileStream(@"\Items.txt", FileMode.Create, FileAccess.ReadWrite, FileShare.ReadWrite); SW = new StreamWriter(FS, Encoding.Default); while (SW.Peek() != -1) { TEMP = (SW.ReadLine()); } but when i try this on Windows-mobile i get error: Error 1 'System.IO.StreamWriter' does not contain a definition for 'Peek' and no extension method 'Peek' accepting a first argument of type 'System.IO.StreamWriter' could be found (are you missing a using directive or an assembly reference?) Error 2 'System.IO.StreamWriter' does not contain a definition for 'ReadLine' and no extension method 'ReadLine' accepting a first argument of type 'System.IO.StreamWriter' could be found (are you missing a using directive or an assembly reference?) how to do it ? thanks

    Read the article

  • net send command program debugging in C#

    - by riad
    Dear all, I write a program to execute and send msg using windows net send command.Its working fine for single receptor.But the problem happen when i want to send message in many receptors. i use a for loop to take receptor name from a list box. Here all message go to the first receptor.The problem happen on process execution.So far i guess the process is not clear or dead on the time. Can any body guide me how i can send the msg to multiple users at a time? my code below: string sendingMessage = messageRichTextBox.Text; string[] recepentAddressArray = new string[recepentAddressListBox.Items.Count]; for (int j = 0; j < recepentAddressListBox.Items.Count; j++) // Getting address from list box { recepentAddressArray[j] = recepentAddressListBox.Items[j].ToString(); string recepantAddress = recepentAddressArray[j]; try { string strLine = "net send " + recepantAddress + " " + sendingMessage + " >C:netsend.log"; FileStream fs = new FileStream("c:netsend.bat", FileMode.Create, FileAccess.Write); StreamWriter streamWriter = new StreamWriter(fs); streamWriter.BaseStream.Seek(0, SeekOrigin.End); streamWriter.Write(strLine); streamWriter.Flush(); streamWriter.Close(); fs.Close(); Process p = new Process(); p.StartInfo.FileName = "C:netsend.bat"; p.StartInfo.WindowStyle = ProcessWindowStyle.Hidden; p.Start(); p.WaitForExit(); p.Close(); FileStream fsOutput = new FileStream("C:netsend.log", FileMode.Open, FileAccess.Read); StreamReader reader = new StreamReader(fsOutput); reader.BaseStream.Seek(0, SeekOrigin.Begin); string strOut = reader.ReadLine(); reader.Close(); fsOutput.Close(); } catch (Exception) { MessageBox.Show("ERROR"); } }

    Read the article

  • Avoiding dispose of underlying stream

    - by danbystrom
    I'm attempting to mock some file operations. In the "real" object I have: StreamWriter createFile( string name ) { return new StreamWriter( Path.Combine( _outFolder, name ), false, Encoding.UTF8 ) ); } In the mock object I'd like to have: StreamWriter createFile( string name ) { var ms = new MemoryStream(); _files.Add( Path.Combine( _outFolder, name ), ms ); return new StreamWriter( ms, Encoding.UTF8 ) ); } where _files is a dictionary to store created files for later inspection. However, when the consumer closes the StreamWriter, it also disposes the MeamoryStream... :-( Any thoughts on how to pursue this?

    Read the article

  • Class Destructor Problem

    - by user279691
    I am making a simple class that contains a StreamWrite class Logger { private StreamWriter sw; private DateTime LastTime; public Logger(string filename) { LastTime = DateTime.Now; sw = new StreamWriter(filename); } public void Write(string s) { sw.WriteLine((DateTime.Now-LastTime).Ticks/10000+":"+ s); LastTime = DateTime.Now; } public void Flush() { sw.Flush(); } ~Logger() { sw.Close();//Raises Exception! } } But when I close this StreamWriter in the destructor, it raises an exception that the StreamWriter was already deleted? Why? And how to make it work such that when the Logger class is deleted, the StreamWriter is closed before deletion? Thanks!

    Read the article

  • How to use Tor control protocol in C#?

    - by Ed
    I'm trying to send commands to the Tor control port programmatically to make it refresh the chain. I haven't been able to find any examples in C#, and my solution's not working. The request times out. I have the service running, and I can see it listening on the control port. public string Refresh() { TcpClient client = new TcpClient("localhost", 9051); string response = string.Empty; string authenticate = MakeTcpRequest("AUTHENTICATE", client); if (authenticate.Equals("250")) response = MakeTcpRequest("SIGNAL NEWNYM", client); client.Close(); return response; } public string MakeTcpRequest(string message, TcpClient client) { client.ReceiveTimeout = 20000; client.SendTimeout = 20000; string proxyResponse = string.Empty; try { // Send message StreamWriter streamWriter = new StreamWriter(client.GetStream()); streamWriter.Write(message); streamWriter.Flush(); // Read response StreamReader streamReader = new StreamReader(client.GetStream()); proxyResponse = streamReader.ReadToEnd(); } catch (Exception ex) { // Ignore } return proxyResponse; } Can anyone spot what I'm doing wrong?

    Read the article

1 2 3 4 5 6 7 8 9 10 11  | Next Page >