Search Results

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

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

  • How to get "AuthSub " token in C#? For google APPS Contacts ?

    - by Pari
    Hi, I fount this code on net : HttpWebRequest update = (HttpWebRequest)WebRequest.Create(**editUrl** ); // editUrl is a string containing the contact's edit URL update.Method = "PUT"; update.ContentType = "application/atom+xml"; update.Headers.Add(HttpRequestHeader.Authorization, "GoogleLogin auth=" + **AuthToken**); update.Headers.Add(HttpRequestHeader.IfMatch, **etag**); // etag is a string containing the <entry> element's gd:etag attribute value update.Headers.Add("GData-Version", "3.0"); Stream streamRequest = update.GetRequestStream(); StreamWriter streamWriter = new StreamWriter(streamRequest, Encoding.UTF8); streamWriter.Write(entry); // entry is the string representation of the atom entry to update streamWriter.Close(); WebResponse response = update.GetResponse(); But here i am not getting what to put in " editurl" , "AuthToken" and "Etag". a) I studied abt "AuthToken" from this Link .But not getting how to create it? Can anyone help me out here? b) Also not getting " editurl" and "Etag". I am trying to use this method to Migrate my contacts to Google Apps. Thanx

    Read the article

  • How to write the content of a dictionary to a text file?

    - by codemonkie
    I have a dictionary object of type Dictionary and trying to use StreamWriter to output the entire content to a text file but failed to find the correct method from the Dictionary class. using (StreamWriter sw = new StreamWriter("myfile.txt")) { sw.WriteLine(dictionary.First()); } I can only retrieve the first element and it is bounded by a square bracket plus a comma separator in between as well: [Peter, Admin] and would be nice to have [Peter Admin] (without the comma)

    Read the article

  • C# - File Encoding Problem.

    - by user301330
    Hello, I'm have a StringBuilder that is writing content to a file. Towards the end of each file, I'm writing the copyright symbol. Oddly, I have noticed that whenever the copyright symbol is written, it is preceeded by a "Â". My code that generates the content of the file looks like this: using (StringWriter stringWriter = new StringWriter()) { stringWriter = GetFileContent(); string targetPath = ConfigurationManager.AppSettings["TargetPath"]; using (StreamWriter streamWriter = new StreamWriter(targetPath, false)) { StringBuilder sb = new StringBuilder(stringWriter.ToString()); // Attempted fix string content = sb.ToString(); content = content.Replace("Â", ""); streamWriter.Write(content); } } As you can tell, I tried to do a find-and-replace. In the process, I noticed that a "Â" was not in the content itself. This makes me believe there is something occurring in the streamWriter. However, I'm not sure what it could be. Can someone please tell me why a "Â" would be popping up before the "©" symbol and how to fix it? I believe it has something to do with encoding, but I'm not sure Thank you!

    Read the article

  • getting aspect related information reg

    - by GowthamanSS
    Suppose i have these structure as class ss { public void createfile() { StreamWriter sw= new StreamWriter("d:/test.txt"); } } i need to do aspect where ever i use StreamWriter? as for as consideration i already used the below code as [assembly: MyAspect(AttributeTargetAssembly="mscorlib", AttributeTargetTypes="System.IO.File", AttributeTargetMembers="Create"] for file.create method .. it works fine .. Is there any way to solve this problem ... waiting for your response

    Read the article

  • Permission issue when webservice deployed as virtual directory.Works in VS IDE

    - by Shyju
    I have an ASP.NET web service which will create a text file in a path which is being passed as a parameter to the method. private void CreateFile(string path) { string strFileName = path; StreamWriter sw = new StreamWriter(strFileName, true); sw.WriteLine(""); sw.Write("Created at " + DateTime.Now.ToString()); sw.Close(); } Now I am passing a folder in the network as the parameter and calling the method CreateFile(@"\\192.168.0.40\\labels\\test.txt"); When running the code from the Visual studio IDE,the file is getting created in the path.But when i published this and deployed as a virtual directoty,Its throwing me some error like "System.UnauthorizedAccessException: Access to the path '\\192.168.0.40\labels\test.txt' is denied. at System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath) at System.IO.FileStream.Init(String path, FileMode mode, FileAccess access, Int32 rights, Boolean useRights, FileShare share, Int32 bufferSize, FileOptions options, SECURITY_ATTRIBUTES secAttrs, String msgPath, Boolean bFromProxy) at System.IO.FileStream..ctor(String path, FileMode mode, FileAccess access, FileShare share, Int32 bufferSize, FileOptions options) at System.IO.StreamWriter.CreateFile(String path, Boolean append) at System.IO.StreamWriter..ctor(String path, Boolean append, Encoding encoding, Int32 bufferSize) at System.IO.StreamWriter..ctor(String path, Boolean append) I have in my web.config.My machine is running in XP and the other is in Windows Server 2003 Any idea to solve this ?? Thanks in advance

    Read the article

  • XML Serialize and Deserialize Problem XML Structure

    - by Ph.E
    Camarades, I'm having the following problem. Caught a list Struct, Serialize (Valid W3C) and send to a WebService. In the WebService I receive, transform to a string, valid by the W3C and then Deserializer, but when I try to run it, always occurs error, saying that some objects were not closed. Any help? Sent Code: #region ListToXML private XmlDocument ListToXMLDocument(object __Lista) { XmlDocument _ListToXMLDocument = new XmlDocument(); try { XmlDocument _XMLDoc = new XmlDocument(); MemoryStream _StreamMem = new MemoryStream(); XmlSerializer _XMLSerial = new XmlSerializer(__Lista.GetType()); StreamWriter _StreamWriter = new StreamWriter(_StreamMem, Encoding.UTF8); _XMLSerial.Serialize(_StreamWriter, __Lista); _StreamMem.Position = 0; _XMLDoc.Load(_StreamMem); if (_XMLDoc.ChildNodes.Count > 0) _ListToXMLDocument = _XMLDoc; } catch (Exception __Excp) { new uException(__Excp).GerarLogErro(CtNomeBiblioteca); } return _ListToXMLDocument; } #endregion Receive Code: #region XMLDocumentToTypedList private List<T> XMLDocumentToTypedList<T>(string __XMLDocument) { List<T> _XMLDocumentToTypedList = new List<T>(); try { XmlSerializer _XMLSerial = new XmlSerializer(typeof(List<T>)); MemoryStream _MemStream = new MemoryStream(); StreamWriter _StreamWriter = new StreamWriter(_MemStream, Encoding.UTF8); _StreamWriter.Write(__XMLDocument); _MemStream.Position = 0; _XMLDocumentToTypedList = (List<T>)_XMLSerial.Deserialize(_MemStream); return _XMLDocumentToTypedList; } catch (Exception _Ex) { new uException(_Ex).GerarLogErro(CtNomeBiblioteca); throw _Ex; } } #endregion

    Read the article

  • How do I find out what process Id and thread id / name has a file open

    - by peter
    Hi All, I am using C# in an application and am having some problems with a file becoming locked. The piece of code does this, while (true) { Read a packet from a socket (with data in it to add to the file) Open a file Writes data to it Close a file } But in the process the file becomes locked. I don't really understand how, we are are definately catching and reporting exceptions so I don't see how the file doesn't get closed every time. My best guess is that something else is opening the file, but I want to prove it. Can someone please provide a piece of code to check whether the file is open and if so report what processid and threadid has the file open. For example if I had this code, StreamWriter streamWriter1 = new StreamWriter(@"c:\logs\test.txt"); streamWriter1.WriteLine("Test"); // code to check for locks?? StreamWriter streamWriter2 = new StreamWriter(@"c:\logs\test.txt"); streamWriter1.Close(); streamWriter2.Close(); That will throw an exception because the file is locked when we try and open it the second time. So where the comment is what could I put in there to report that the current app (process Id) and the current thread (thread Id) have the file locked? Thanks.

    Read the article

  • WCF and ASP.NET - Server.Execute throwing object reference not set to an instance of an object

    - by user208662
    Hello, I have an ASP.NET page that calls to a WCF service. This WCF service uses a BackgroundWorker to asynchronously create an ASP.NET page on my server. Oddly, when I execute the WCF Service [OperationContract] [WebInvoke(Method = "POST", BodyStyle = WebMessageBodyStyle.WrappedRequest, RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json)] public void PostRequest(string comments) { // Do stuff // If everything went o.k. asynchronously render a page on the server. I do not want to // block the caller while this is occurring. BackgroundWorker myWorker = new BackgroundWorker(); myWorker.DoWork += new DoWorkEventHandler(myWorker_DoWork); myWorker.RunWorkerAsync(HttpContext.Current); } private void myWorker_DoWork(object sender, DoWorkEventArgs e) { // Set the current context so we can render the page via Server.Execute HttpContext context = (HttpContext)(e.Argument); HttpContext.Current = context; // Retrieve the url to the page string applicationPath = context.Request.ApplicationPath; string sourceUrl = applicationPath + "/log.aspx"; string targetDirectory = currentContext.Server.MapPath("/logs/"); // Execute the other page and load its contents using (StringWriter stringWriter = new StringWriter()) { // Write the contents out to the target url // NOTE: THIS IS WHERE MY ERROR OCCURS currentContext.Server.Execute(sourceUrl, stringWriter); // Prepare to write out the result of the log targetPath = targetDirectory + "/" + DateTime.Now.ToShortDateString() + ".aspx"; using (StreamWriter streamWriter = new StreamWriter(targetPath, false)) { // Write out the content to the file sb.Append(stringWriter.ToString()); streamWriter.Write(sb.ToString()); } } } Oddly, when the currentContext.Server.Execute method is executed, it throws an "object reference not set to an instance of an object" error. The reason this is so strange is because I can look at the currentContext properties in the watch window. In addition, Server is not null. Because of this, I have no idea where this error is coming from. Can someone point me in the correct direction of what the cause of this could be? Thank you!

    Read the article

  • WebRequest using SSL

    - by pm_2
    I have the following code to retrieve a file using FTP (which works fine). FtpWebRequest request = (FtpWebRequest)WebRequest.Create(svrPath); request.KeepAlive = true; request.UsePassive = true; request.UseBinary = true; request.Method = WebRequestMethods.Ftp.DownloadFile; request.Credentials = new NetworkCredential(uname, passw); using (FtpWebResponse response = (FtpWebResponse)request.GetResponse()) using (Stream responseStream = response.GetResponseStream()) using (StreamReader reader = new StreamReader(responseStream)) using (StreamWriter destination = new StreamWriter(destinationFile)) { destination.Write(reader.ReadToEnd()); destination.Flush(); } However, when I try to do this using SSL, I am unable to access the file, as follows: FtpWebRequest request = (FtpWebRequest)WebRequest.Create(svrPath); request.KeepAlive = true; request.UsePassive = true; request.UseBinary = true; // The following line causes the download to fail request.EnableSsl = true; request.Method = WebRequestMethods.Ftp.DownloadFile; request.Credentials = new NetworkCredential(uname, passw); using (FtpWebResponse response = (FtpWebResponse)request.GetResponse()) using (Stream responseStream = response.GetResponseStream()) using (StreamReader reader = new StreamReader(responseStream)) using (StreamWriter destination = new StreamWriter(destinationFile)) { destination.Write(reader.ReadToEnd()); destination.Flush(); } Can anyone tell me why the latter would not work?

    Read the article

  • GZipStream in an WebHttpResponse producing no data

    - by Pierre 303
    I want to compress my HTTP Responses for client that supports it. Here is the code used to send a standard response: IHttpClientContext context = (IHttpClientContext)sender; IHttpRequest request = e.Request; string responseBody = "This is some random text"; IHttpResponse response = request.CreateResponse(context); using (StreamWriter writer = new StreamWriter(response.Body)) { writer.WriteLine(responseBody); writer.Flush(); response.Send(); } The code above works fine. Now I added gzip support below. When I test it with a browser that supports gzip or a custom method, it returns an empty string. I'm sure I'm missing something simple, but I just can't find it... IHttpClientContext context = (IHttpClientContext)sender; IHttpRequest request = e.Request; string acceptEncoding = request.Headers["Accept-Encoding"]; string responseBody = "This is some random text"; IHttpResponse response = request.CreateResponse(context); if (acceptEncoding != null && acceptEncoding.Contains("gzip")) { byte[] bytes = ASCIIEncoding.ASCII.GetBytes(responseBody); response.AddHeader("Content-Encoding", "gzip"); using (GZipStream writer = new GZipStream(response.Body, CompressionMode.Compress)) { writer.Write(bytes, 0, bytes.Length); writer.Flush(); response.Send(); } } else { using (StreamWriter writer = new StreamWriter(response.Body)) { writer.WriteLine(responseBody); writer.Flush(); response.Send(); } }

    Read the article

  • Is MSDN referencing a system.thread, a worker thread, an io thread or all three?

    - by w0051977
    Please see the warning below taken from the StreamWriter class specification (http://msdn.microsoft.com/en-us/library/system.io.streamwriter.aspx): "Any public static (Shared in Visual Basic) members of this type are thread safe. Any instance members are not guaranteed to be thread safe." I understand that a W3WC process contains two thread pools i.e. worker threads and I/O threads. A worker thread could contain many threads of its own (if the application creates its own System.Thread instances). Does the warning only relate to System.Threads or does it relate to worker threads and I/O threads as well I.e. as the instance variables of the streamwriter class are not thread safe then does this mean that there would be problems if multiple worker threads access it eg if two users on two different web clients attempt to write to the log file at the same time, then could one lock out the other?

    Read the article

  • Isolated Storage Made Easy

    In its most simple form Isolated Storage allows you to save name value pairs and retrieve them at some other time the next time your app runs. Granted we could get into XML and text files etc but I'm going to stick with just name value pairs. Lets take a look at this line:private void PresistKeyValue(string _Key, string _Value){StreamWriter MyWriter = new StreamWriter(new IsolatedStorageFileStream(_Key, FileMode.Create, IsolatedStorageFile.GetUserStoreForApplication()));MyWriter.Write(_Value);MyWriter.Close();}Nice...Did you know that DotNetSlackers also publishes .net articles written by top known .net Authors? We already have over 80 articles in several categories including Silverlight. Take a look: here.

    Read the article

  • quickly close all word and excel

    - by dyenatha
    Suppose I open 10 Word files and 10 Excel files and make no changes, how do I quickly taskkill all at once? Because I must repeat several attempts to replicate race, I'm hoping for a command-line solution. I'm willing to try PowerShell and cygwin (1.5) if necessary. The OS is Windows XP SP3 with current patches (still IE7). I tried "taskkill /pid 1 /pid 2 /t" where 1 is PID of EXCEL.EXE and 2 is PID of WINWORD.EXE, but it closed only 1 window of each program. I'm trying to replicate a race where an add-in for Microsoft Office 2007 fails to exclusive-lock one of its own files, which caused the 2nd Office program to stop exiting with a warning: System.IO.IOException: The process cannot access the file 'C:\Documents and Settings\me\Application Data\ExpensiveProduct\Add-InForMicrosoftOffice\4.2\egcred' because it is being used by another process. at System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath) at System.IO.FileStream.Init(String path, FileMode mode, FileAccess access, Int32 rights, Boolean useRights, FileShare share, Int32 bufferSize, FileOptions options, SECURITY_ATTRIBUTES secAttrs, String msgPath, Boolean bFromProxy) at System.IO.FileStream..ctor(String path, FileMode mode, FileAccess access, FileShare share, Int32 bufferSize, FileOptions options) at System.IO.StreamWriter.CreateFile(String path, Boolean append) at System.IO.StreamWriter..ctor(String path, Boolean append, Encoding encoding, Int32 bufferSize) at System.IO.StreamWriter..ctor(String path, Boolean append, Encoding encoding) at System.IO.File.WriteAllText(String path, String contents, Encoding encoding) at ExpensiveProduct.EG.DataAccess.Credentials.CredentialManager.SaveUserTable() at ExpensiveProduct.OfficeAddin.OfficeAddinBase.Dispose(Boolean disposing) at ExpensiveProduct.OfficeAddin.WordAddin.Dispose(Boolean disposing) at ExpensiveProduct.OfficeAddin.OfficeAddinBase.OnHostShutdown() at ExpensiveProduct.OfficeAddin.OfficeAddinBase.Unload(ext_DisconnectMode mode)

    Read the article

  • Quickly close all Word and Excel instances?

    - by dyenatha
    Suppose I open 10 Word files and 10 Excel files and make no changes, how do I quickly taskkill all at once? Because I must repeat several attempts to replicate race, I'm hoping for a command-line solution. I'm willing to try PowerShell and cygwin (1.5) if necessary. The OS is Windows XP SP3 with current patches (still IE7). I tried "taskkill /pid 1 /pid 2 /t" where 1 is PID of EXCEL.EXE and 2 is PID of WINWORD.EXE, but it closed only 1 window of each program. I'm trying to replicate a race where an add-in for Microsoft Office 2007 fails to exclusive-lock one of its own files, which caused the 2nd Office program to stop exiting with a warning: System.IO.IOException: The process cannot access the file 'C:\Documents and Settings\me\Application Data\ExpensiveProduct\Add-InForMicrosoftOffice\4.2\egcred' because it is being used by another process. at System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath) at System.IO.FileStream.Init(String path, FileMode mode, FileAccess access, Int32 rights, Boolean useRights, FileShare share, Int32 bufferSize, FileOptions options, SECURITY_ATTRIBUTES secAttrs, String msgPath, Boolean bFromProxy) at System.IO.FileStream..ctor(String path, FileMode mode, FileAccess access, FileShare share, Int32 bufferSize, FileOptions options) at System.IO.StreamWriter.CreateFile(String path, Boolean append) at System.IO.StreamWriter..ctor(String path, Boolean append, Encoding encoding, Int32 bufferSize) at System.IO.StreamWriter..ctor(String path, Boolean append, Encoding encoding) at System.IO.File.WriteAllText(String path, String contents, Encoding encoding) at ExpensiveProduct.EG.DataAccess.Credentials.CredentialManager.SaveUserTable() at ExpensiveProduct.OfficeAddin.OfficeAddinBase.Dispose(Boolean disposing) at ExpensiveProduct.OfficeAddin.WordAddin.Dispose(Boolean disposing) at ExpensiveProduct.OfficeAddin.OfficeAddinBase.OnHostShutdown() at ExpensiveProduct.OfficeAddin.OfficeAddinBase.Unload(ext_DisconnectMode mode)

    Read the article

  • Windows Azure: Creation of a file on cloud blob container

    - by veda
    I am writing a program that will be executing on the cloud. The program will generate an output that should be written on to a file and the file should be saved on the blob container. I don't have a idea of how to do that Will this code FileStream fs = new FileStream(file, FileMode.Create); StreamWriter sw = new StreamWriter(fs); generate a file named "file" on the cloud...

    Read the article

  • Refactor instance declaration from try block to above try block in a method

    - by dotnetdev
    Hi, Often I find myself coming across code like this: try { StreamWriter strw = new StreamWriter(); } However, there is no reference to the object outside the scope of the try block. How could I refactor (extract to field in Visual Studio says there is no field or something) the statement in the try block so that it is declared above the try block so I can use it anywhere in the method? Thanks

    Read the article

  • SaveFileDialog problem (C#) (VS2008)

    - by typoknig
    Hi all, I am having an issue with SaveFileDialog for some reason. All I want to do is extract data from a text box line by line and write it to a text file, then save that text file to the desktop. The first bit of code works fine (though it doesn't save to the desktop). The second bit of code is what I want to use, but when it creates the text file the text file is empty. What did I do wrong in my second bit of code? This code works, but it does not save to the desktop and it isn't as nice as the second code. //When the Save button is clicked the contents of the text box will be written to a text file. private void saveButton_Click(object sender, EventArgs e) { int textBoxLines = textBox.Lines.Count(); if (File.Exists(saveFile)) { result = MessageBox.Show("The file " + saveFile + " already exists.\r\nDo you want to replace it?", "File Already Exists!", MessageBoxButtons.YesNo); if (result == DialogResult.Yes) { TextWriter tw1 = new StreamWriter(saveFile); for (int i = 0; i < textBoxLines; i++) { tw1.WriteLine(textBox.Lines.GetValue(i)); } tw1.Close(); } if (result == DialogResult.No) { MessageBox.Show("Please move or rename existing " + saveFile + "\r\nBefore attempting to save again.", "Message"); } } else { TextWriter tw2 = new StreamWriter(saveFile); for (int i = 0; i < textBoxLines; i++) { tw2.WriteLine(textBox.Lines.GetValue(i)); } tw2.Close(); } } This code does not work, but it is what I want to use. //When the Save button is clicked the contents of the text box will be written to a text file. private void saveButton_Click(object sender, EventArgs e) { int textBoxLines = textBox.Lines.Count(); Stream saveStream; SaveFileDialog saveDialog = new SaveFileDialog(); saveDialog.Filter = "txt files (*.txt)|*.txt|All files (*.*)|*.*"; saveDialog.FilterIndex = 2; saveDialog.RestoreDirectory = true; saveDialog.FileName = (saveFile); saveDialog.InitialDirectory = (Environment.GetFolderPath(Environment.SpecialFolder.Desktop)); if (saveDialog.ShowDialog() == DialogResult.OK) { if ((saveStream = saveDialog.OpenFile()) != null) { StreamWriter tw = new StreamWriter(saveStream); for (int i = 0; i < textBoxLines; i++) { tw.WriteLine(textBox.Lines.GetValue(i)); } saveStream.Close(); } } }

    Read the article

  • Try catch finally blocks.. do i still need them?

    - by Phil
    I am handling errors via my global.asax in this method: Dim CurrentException As Exception CurrentException = Server.GetLastError() Dim LogFilePath As String = Server.MapPath("~/Error/" & DateTime.Now.ToString("dd-MM-yy.HH.mm") & ".txt") Dim sw As System.IO.StreamWriter = New System.IO.StreamWriter(LogFilePath) sw.WriteLine(DateTime.Now.ToString) sw.WriteLine(CurrentException.ToString()) sw.Close() In my code I currently have no other error handling. Should I still insert try, catch, finally blocks? Thanks.

    Read the article

  • How can i learn file name and create a folder?

    - by Phsika
    i try to make TCP/Ip Application to listen any other roemote computer to recieve any file. So i try to get files. i can do that. on the other hand every sample on google about giving SaveDialogBox to recived path folder.Forexample my old server.cs is that: using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; using System.IO; using System.Net; using System.Net.Sockets; using System.Threading; namespace Server3 { public partial class Form1 : Form { Thread kanal; public Form1() { InitializeComponent(); try { kanal = new Thread(new ThreadStart(Dinle)); kanal.Start(); kanal.Priority = ThreadPriority.Normal; this.Text = "Kanal Çalisti"; } catch (Exception ex) { this.Text = "kanal çalismadi"; MessageBox.Show("hata:" + ex.ToString()); kanal.Abort(); throw; } } void Dinle() { TcpListener server = null; try { Int32 port = 51124; IPAddress localAddr = IPAddress.Parse("127.0.0.1"); server = new TcpListener(localAddr, port); server.Start(); Byte[] bytes = new Byte[1024 * 250000]; // string ReceivedPath = "C:/recieved"; while (true) { MessageBox.Show("Waiting for a connection... "); TcpClient client = server.AcceptTcpClient(); MessageBox.Show("Connected!"); NetworkStream stream = client.GetStream(); if (stream.CanRead) { saveFileDialog1.ShowDialog(); string pathfolder = saveFileDialog1.FileName; StreamWriter yaz = new StreamWriter(pathfolder); string satir; StreamReader oku = new StreamReader(stream); while ((satir = oku.ReadLine()) != null) { satir = satir + (char)13 + (char)10; yaz.WriteLine(satir); } oku.Close(); yaz.Close(); client.Close(); } } } catch (SocketException e) { Console.WriteLine("SocketException: {0}", e); } finally { // Stop listening for new clients. server.Stop(); } Console.WriteLine("\nHit enter to continue..."); Console.Read(); } private void Form1_Load(object sender, EventArgs e) { Dinle(); } } } i want to give automatically folder without SAVEDIALOGBOX. Also i want to learn my file name om my stream.Like that: using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; using System.IO; using System.Net; using System.Net.Sockets; using System.Threading; namespace Server3 { public partial class Form1 : Form { Thread kanal; public Form1() { InitializeComponent(); try { kanal = new Thread(new ThreadStart(Dinle)); kanal.Start(); kanal.Priority = ThreadPriority.Normal; this.Text = "Kanal Çalisti"; } catch (Exception ex) { this.Text = "kanal çalismadi"; MessageBox.Show("hata:" + ex.ToString()); kanal.Abort(); throw; } } void Dinle() { TcpListener server = null; try { Int32 port = 51124; IPAddress localAddr = IPAddress.Parse("127.0.0.1"); server = new TcpListener(localAddr, port); server.Start(); Byte[] bytes = new Byte[1024 * 250000]; string ReceivedPath = "C:/recieved"; while (true) { MessageBox.Show("Waiting for a connection... "); TcpClient client = server.AcceptTcpClient(); MessageBox.Show("Connected!"); NetworkStream stream = client.GetStream(); if (stream.CanRead) { saveFileDialog1.ShowDialog(); string pathfolder = " i have to give property creating path and want to learn file name"; StreamWriter yaz = new StreamWriter(pathfolder); string satir; StreamReader oku = new StreamReader(stream); while ((satir = oku.ReadLine()) != null) { satir = satir + (char)13 + (char)10; yaz.WriteLine(satir); } oku.Close(); yaz.Close(); client.Close(); } } } catch (SocketException e) { Console.WriteLine("SocketException: {0}", e); } finally { // Stop listening for new clients. server.Stop(); } Console.WriteLine("\nHit enter to continue..."); Console.Read(); } private void Form1_Load(object sender, EventArgs e) { Dinle(); } } } Also i need : FileStream fs; FileInfo fi = new FileInfo(@"c:/recieved"); if (fi.Exists) fs = new FileStream(fi.FullName, FileMode.Append); else fs = new FileStream(fi.FullName, FileMode.Create); StreamWriter yazici = new StreamWriter(fs); How can i do that. Creating C:/recieved if it does not exist. And how can i learn File name on my network stream sending File Name.

    Read the article

  • StackOverFlow Exception while Writing the Object Graph in to XAML

    - by Jose
    I am trying to Write an object stream into a XAML file but i end up in StackoverFlowException . In the CallStack i could see "The maximum number of stack frames supported by Visual Studio has been exceeded" This is the piece of code i'm trying to execute. StreamWriter xamlStream =new StreamWriter(File.OpenWrite("a.xaml")); string myXaml = System.Windows.Markup.XamlWriter.Save(objectInstance); xamlStream.Write(myXaml); Thanks ...!

    Read the article

  • Writing text file on local server MVC 2.0

    - by Liado
    Hi, i'm trying to write a text file on remote server, i'm using the following code: [AcceptVerbs(HttpVerbs.Post)] public ActionResult Index(UserModels model) { if (!ModelState.IsValid) { return View("Index"); } try { using (StreamWriter w = new StreamWriter(Server.MapPath(TEXT_FILE_NAME), true)) { w.WriteLine(model.Email.ToString()); // Write the text } } catch { } the folder is still empty, can someone help? what should be the problem? Thanks

    Read the article

  • C# StreamReader.EndOfStream produces IOException

    - by Ziplin
    I'm working on an application that accepts TCP connections and reads in data until an </File> marker is read and then writes that data to the filesystem. I don't want to disconnect, I want to let the client sending the data to do that so they can send multiple files in one connection. I'm using the StreamReader.EndOfStream around my outter loop, but it throws an IOException when the client disconnects. Is there a better way to do this? private static void RecieveAsyncStream(IAsyncResult ar) { TcpListener listener = (TcpListener)ar.AsyncState; TcpClient client = listener.EndAcceptTcpClient(ar); // init the streams NetworkStream netStream = client.GetStream(); StreamReader streamReader = new StreamReader(netStream); StreamWriter streamWriter = new StreamWriter(netStream); while (!streamReader.EndOfStream) // throws IOException { string file= ""; while (file!= "</File>" && !streamReader.EndOfStream) { file += streamReader.ReadLine(); } // write file to filesystem } listener.BeginAcceptTcpClient(RecieveAsyncStream, listener); }

    Read the article

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