Search Results

Search found 460 results on 19 pages for 'streamreader'.

Page 10/19 | < Previous Page | 6 7 8 9 10 11 12 13 14 15 16 17  | Next Page >

  • how to monitor the program code execution? (file creation and modification by code lines etc)

    - by infant programmer
    My program is about triggering XSL transformation, Its fact that this code for carrying out the transformation, creates some dll and tmp files and deletes them pretty soon after the transformation is completed. It is almost untraceable for me to monitor the creation and deletion of files manually, so I want to include some chunk of codelines to display "which codeline has created/modified which tmp and dll files" in console window. This is the relevant part of the code: string strXmlQueryTransformPath = @"input.xsl"; string strXmlOutput = string.Empty; StringReader srXmlInput = null; StringWriter swXmlOutput = null; XslCompiledTransform xslTransform = null; XPathDocument xpathXmlOrig = null; XsltSettings xslSettings = null; MemoryStream objMemoryStream = null; objMemoryStream = new MemoryStream(); xslTransform = new XslCompiledTransform(false); xpathXmlOrig = new XPathDocument("input.xml"); xslSettings = new XsltSettings(); xslSettings.EnableScript = true; xslTransform.Load(strXmlQueryTransformPath, xslSettings, new XmlUrlResolver()); xslTransform.Transform(xpathXmlOrig, null, objMemoryStream); objMemoryStream.Position = 0; StreamReader objStreamReader = new StreamReader(objMemoryStream); strXmlOutput = objStreamReader.ReadToEnd(); // make use of Data in string "strXmlOutput" google and msdn search couldn't help me much..

    Read the article

  • Listview not being populated

    - by Luke
    I have put some console.writeline code in to test, but they arent appearing in the output box? public static ArrayList myDeliveries = new ArrayList(); public mainForm() { InitializeComponent(); } private void mainForm_Load(object sender, EventArgs e) { if (!File.Exists("../../MealDeliveries.txt")) { MessageBox.Show("File not found!"); return; } using (StreamReader sr = new StreamReader("../../MealDeliveries.txt")) { //first line is delivery name string strDeliveryName = sr.ReadLine(); Console.WriteLine("some tetttttttttt23423423423423423ttttttttttttttttttttttt"); while (strDeliveryName != null) { //other lines Delivery d = new Delivery(strDeliveryName, sr.ReadLine(), sr.ReadLine(), sr.ReadLine(), sr.ReadLine(), sr.ReadLine(), sr.ReadLine()); mainForm.myDeliveries.Add(d); //check for further values strDeliveryName = sr.ReadLine(); } } displayDeliveries(); } private void displayDeliveries() { lstDeliveryDetails.Items.Clear(); Console.WriteLine("some tettttttttttttttttttttttttttttttttt"); Console.WriteLine(mainForm.myDeliveries.Count); foreach (Delivery d in mainForm.myDeliveries) { lstDeliveryDetails.Items.Add(d.DeliveryName); } } Can anyone help??

    Read the article

  • Why Response.Write behavior varies in the given scenario?

    - by Sri Kumar
    Hello All, When i POST the page using the following code, the Response.write("Hey") doesn't write the content ("Hello") to the parent page <form method="post" name="upload" enctype="multipart/form-data" action="http://localhost:2518/Web/CrossPage.aspx?cmd=getvalue" > <input type="file" name="filename" /> <input type="submit" value="Upload Data File" name="cmdSubmit" /> </form> But When i use following code , and POST the data, the Response.write("Hey") can be obtained in the parent page HttpWebRequest requestToSender = (HttpWebRequest)WebRequest.Create("http://localhost:2518/Web/CrossPage.aspx?cmd=getvalue"); requestToSender.Method = "POST"; requestToSender.ContentType = "multipart/form-data"; HttpWebResponse responseFromSender = (HttpWebResponse)requestToSender.GetResponse(); string fromSender = string.Empty; using (StreamReader responseReader = new StreamReader(responseFromSender.GetResponseStream())) { fromSender = responseReader.ReadToEnd(); } In the CrossPage.aspx i have the following code if (!Page.IsPostBack) { NameValueCollection postPageCollection = Request.Form; foreach (string name in postPageCollection.AllKeys) { Response.Write(name + " " + postPageCollection[name]); } HttpFileCollection postCollection = Request.Files; foreach (string name in postCollection.AllKeys) { HttpPostedFile aFile = postCollection[name]; aFile.SaveAs(Server.MapPath(".") + "/" + Path.GetFileName(aFile.FileName)); } Response.Write("Hey"); } I don't have any code in the Page_Load event of parent page.? What could be the cause? I need to write the "hey" to the Parent page using the first scenario. Both the application are of different domain. Edit: "Hey" would be from the CrossPage.aspx. I need to write this back to the Parent Page

    Read the article

  • How to retain similar character encoding

    - by Mystere Man
    I have a logfile that contains the half character ½, I need to process this log file and rewrite certain lines to a new file, which contain that character. However, when I write out the file the characters appear in notepad incorrectly. I know this is some kind of encoding issue, and i'm not sure if it's just that the files i'm writing don't contain the correct bom or what. I've tried reading and writing the file with all the available encoding options in the Encoding enumeration. I'm using this code: string line; // Note i've used every version of the Encoding enumeration using (StreamReader sr = new StreamReader(file, Encoding.Unicode)) using (StreamWRiter sw = new StreamWriter(newfile, false, Encoding.Unicode)) { while ((line = sr.ReadLine()) != null) { // process code, I do not alter the lines, they are copied verbatim // but i do not write every line that i read. sw.WriteLine(line); } } When I view the original log in notepad, the half character displays correctly. When I view the new file, it does not. Can anyone help me to solve this?

    Read the article

  • Why this C# Regular Expression crashes my program?

    - by robert_d
    using System; using System.IO; using System.Net; using System.Text.RegularExpressions; namespace Working { class Program4 { static string errorurl = "http://www.realtor.ca/propertyDetails.aspx?propertyId=8692663"; static void Main(string[] args) { string s; s = getWebpageContent(errorurl); s = removeNewLineCharacters(s); getFields(s); Console.WriteLine("End"); } public static void getFields(string html) { Match m; string fsRE = @"ismeasurement.*?>.*?(\d+).*?sqft"; m = Regex.Match(html, fsRE, RegexOptions.IgnoreCase); } private static string removeNewLineCharacters(string str) { string[] charsToRemove = new string[] { "\n", "\r" }; foreach (string c in charsToRemove) { str = str.Replace(c, ""); } return str; } static string getWebpageContent(string url) { WebClient client = new WebClient(); client.Headers.Add("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; .NET CLR 1.0.3705;)"); Stream data = client.OpenRead(url); StreamReader reader = new StreamReader(data); string s = reader.ReadToEnd(); data.Close(); reader.Close(); return s; } } } This program hangs. It runs correctly when I remove RegexOptions.IgnoreCase option or when I remove call to removeNewLineCharacters() function. Could someone tell me what is going on, please?

    Read the article

  • Named pipe stalls threads?

    - by entens
    I am attempting to push updates into a process via a named pipe, but in doing so my process loop now seams to stall on while ((line = sr.ReadLine()) != null). I'm a little mystified as to what might be wrong as this is my first foray into named pipes. void RefreshThread() { using (NamedPipeServerStream pipeStream = new NamedPipeServerStream("processPipe", PipeDirection.In)) { pipeStream.WaitForConnection(); using (StreamReader sr = new StreamReader(pipeStream)) { for (; ; ) { if (StopThread == true) { StopThread = false; return; // exit loop and terminate the thread } // push update for heartbeat int HeartbeatHandle = ItemDictionary["Info.Heartbeat"]; int HeartbeatValue = (int)Config.Items[HeartbeatHandle].Value; Config.Items[HeartbeatHandle].Value = ++HeartbeatValue; SetItemValue(HeartbeatHandle, HeartbeatValue, (short)0xC0, DateTime.Now); string line = null; while ((line = sr.ReadLine()) != null) { // line is in the format: item, value, timestamp string[] parts = line.Split(','); // push update and store value in item cache int handle = ItemDictionary[parts[0]]; object value = parts[1]; Config.Items[handle].Value = int.Parse(value); DateTime timestamp = DateTime.FromBinary(long.Parse(parts[2])); SetItemValue(handle, value, (short)0xC0, timestamp); } Thread.Sleep(500); } } } }

    Read the article

  • C# XML node with colon

    - by Sticky
    Hi, my code attempts to grab data from the RSS feed of a website. It grabs the nodes fine, but when attempting to grab the data from a node with a colon, it crashes and gives the error "Namespace Manager or XsltContext needed. This query has a prefix, variable, or user-defined function." The code is shown below: WebRequest request = WebRequest.Create("http://buypoe.com/external.php?type=RSS2&lastpost=true"); WebResponse response = request.GetResponse(); StringBuilder sb = new StringBuilder(""); System.IO.StreamReader rssStream = new System.IO.StreamReader(response.GetResponseStream(), System.Text.Encoding.GetEncoding("utf-8")); XmlDocument rssDoc = new XmlDocument(); rssDoc.Load(rssStream); XmlNodeList rssItems = rssDoc.SelectNodes("rss/channel/item"); for (int i = 0; i < 5; i++) { XmlNode rssDetail; rssDetail = rssItems.Item(i).SelectSingleNode("dc:creator"); if (rssDetail != null) { user = rssDetail.InnerText; } else { user = ""; } } I understand that I need to define the namespace, but am unsure how to do this. Help would be appreciated.

    Read the article

  • Stuck in a loop

    - by Luke
    while (true) { //read in the file StreamReader convert = new StreamReader("../../convert.txt"); //define variables string line = convert.ReadLine(); double conversion; int numberIn; double conversionFactor; //ask for the conversion information Console.WriteLine("Enter the conversion in the form (Amount, Convert from, Convert to)"); String inputMeasurement = Console.ReadLine(); string[] inputMeasurementArray = inputMeasurement.Split(','); //loop through the lines looking for a match while (line != null) { string[] fileMeasurementArray = line.Split(','); if (fileMeasurementArray[0] == inputMeasurementArray[1]) { if (fileMeasurementArray[1] == inputMeasurementArray[2]) { Console.WriteLine("The conversion factor for {0} to {1} is {2}", inputMeasurementArray[1], inputMeasurementArray[2], fileMeasurementArray[2]); //convert to int numberIn = Convert.ToInt32(inputMeasurementArray[0]); conversionFactor = Convert.ToDouble(fileMeasurementArray[2]); conversion = (numberIn * conversionFactor); Console.WriteLine("{0} {1} is {2} {3} \n", inputMeasurementArray[0], inputMeasurementArray[1], conversion, inputMeasurementArray[2]); break; } } else { Console.WriteLine("Please enter two valid conversion types \n"); break; } line = convert.ReadLine(); } } The file consists of the following: ounce,gram,28.0 pound,ounce,16.0 pound,kilogram,0.454 pint,litre,0.568 inch,centimetre,2.5 mile,inch,63360.0 The user will input something like 6,ounce,gram The idea is that it finds the correct line by checking if the first and second words in the file are the same as the second and third the user enters. The problem is that if it checks the first line and it fails the if statement, if goes through to the else statement and stops. I am trying to find a way where it will stop after the it finds the correct line but not until. If someone types in a value that isn't in the file, then it should show an error.

    Read the article

  • How to Avoid Server Error 414 for Very Long QueryString Values

    - by Registered User
    I had a project that required posting a 2.5 million character QueryString to a web page. The server itself only parsed URI's that were 5,400 characters or less. After trying several different sets of code for WebRequest/WebResponse, WebClient, and Sockets, I finally found the following code that solved my problem: HttpWebRequest webReq; HttpWebResponse webResp = null; string Response = ""; Stream reqStream = null; webReq = (HttpWebRequest)WebRequest.Create(strURL); Byte[] bytes = Encoding.UTF8.GetBytes("xml_doc=" + HttpUtility.UrlEncode(strQueryString)); webReq.ContentType = "application/x-www-form-urlencoded"; webReq.Method = "POST"; webReq.ContentLength = bytes.Length; reqStream = webReq.GetRequestStream(); reqStream.Write(bytes, 0, bytes.Length); reqStream.Close(); webResp = (HttpWebResponse)webReq.GetResponse(); if (webResp.StatusCode == HttpStatusCode.OK) { StreamReader loResponseStream = new StreamReader(webResp.GetResponseStream(), Encoding.UTF8); Response = loResponseStream.ReadToEnd(); } webResp.Close(); reqStream = null; webResp = null; webReq = null;

    Read the article

  • My C# UploadFile method successfully uploads a file, but then my UI hangs...

    - by kyrathaba
    I have a simple WinForms test application in C#. Using the following method, I'm able to upload a file when I invoke the method from my button's Click event handler. The only problem is: my Windows Form "freezes". I can't close it using the Close button. I have to end execution from within the IDE (Visual C# 2010 Express edition). Here are the two methods: public void UploadFile(string FullPathFilename) { string filename = Path.GetFileName(FullPathFilename); try { FtpWebRequest request = (FtpWebRequest)WebRequest.Create(_remoteHost + filename); request.Method = WebRequestMethods.Ftp.UploadFile; request.Credentials = new NetworkCredential(_remoteUser, _remotePass); StreamReader sourceStream = new StreamReader(FullPathFilename); byte[] fileContents = Encoding.UTF8.GetBytes(sourceStream.ReadToEnd()); request.ContentLength = fileContents.Length; Stream requestStream = request.GetRequestStream(); requestStream.Write(fileContents, 0, fileContents.Length); FtpWebResponse response = (FtpWebResponse)request.GetResponse(); response.Close(); requestStream.Close(); sourceStream.Close(); } catch (Exception ex) { MessageBox.Show(ex.Message, "Upload error"); } finally { } } which gets called here: private void btnUploadTxtFile_Click(object sender, EventArgs e) { string username = "my_username"; string password = "my_password"; string host = "ftp://mywebsite.com"; try { clsFTPclient client = new clsFTPclient(host + "/httpdocs/non_church/", username, password); client.UploadFile(Path.GetDirectoryName(Application.ExecutablePath) + "\\myTextFile.txt"); } catch (Exception ex) { MessageBox.Show(ex.Message, "Upload problem"); } }

    Read the article

  • Binary serialization and deserialization without creating files (via strings)

    - by the_V
    Hi, I'm trying to create a class that will contain functions for serializing/deserializing objects to/from string. That's what it looks like now: public class BinarySerialization { public static string SerializeObject(object o) { string result = ""; if ((o.GetType().Attributes & TypeAttributes.Serializable) == TypeAttributes.Serializable) { BinaryFormatter f = new BinaryFormatter(); using (MemoryStream str = new MemoryStream()) { f.Serialize(str, o); str.Position = 0; StreamReader reader = new StreamReader(str); result = reader.ReadToEnd(); } } return result; } public static object DeserializeObject(string str) { object result = null; byte[] bytes = System.Text.Encoding.ASCII.GetBytes(str); using (MemoryStream stream = new MemoryStream(bytes)) { BinaryFormatter bf = new BinaryFormatter(); result = bf.Deserialize(stream); } return result; } } SerializeObject method works well, but DeserializeObject does not. I always get an exception with message "End of Stream encountered before parsing was completed". What may be wrong here?

    Read the article

  • Help me convert .NET 1.1 Xml validation code to .NET 2.0 please.

    - by Hamish Grubijan
    It would be fantastic if you could help me rid of these warnings below. I have not been able to find a good document. Since the warnings are concentrated in just the private void ValidateConfiguration( XmlNode section ) section, hopefully this is not terribly hard to answer, if you have encountered this before. Thanks! 'System.Configuration.ConfigurationException.ConfigurationException(string)' is obsolete: 'This class is obsolete, to create a new exception create a System.Configuration!System.Configuration.ConfigurationErrorsException' 'System.Xml.XmlValidatingReader' is obsolete: 'Use XmlReader created by XmlReader.Create() method using appropriate XmlReaderSettings instead. http://go.microsoft.com/fwlink/?linkid=14202' private void ValidateConfiguration( XmlNode section ) { // throw if there is no configuration node. if( null == section ) { throw new ConfigurationException("The configuration section passed within the ... class was null ... there must be a configuration file defined.", section ); } //Validate the document using a schema XmlValidatingReader vreader = new XmlValidatingReader( new XmlTextReader( new StringReader( section.OuterXml ) ) ); // open stream on Resources; the XSD is set as an "embedded resource" so Resource can open a stream on it using (Stream xsdFile = XYZ.GetStream("ABC.xsd")) using (StreamReader sr = new StreamReader(xsdFile)) { vreader.ValidationEventHandler += new ValidationEventHandler(ValidationCallBack); vreader.Schemas.Add(XmlSchema.Read(new XmlTextReader(sr), null)); vreader.ValidationType = ValidationType.Schema; // Validate the document while (vreader.Read()) { } if (!_isValidDocument) { _schemaErrors = _sb.ToString(); throw new ConfigurationException("XML Document not valid"); } } } // Does not cause warnings. private void ValidationCallBack( object sender, ValidationEventArgs args ) { // check what KIND of problem the schema validation reader has; // on FX 1.0, it gives a warning for "<xs:any...skip" sections. Don't worry about those, only set validation false // for real errors if( args.Severity == XmlSeverityType.Error ) { _isValidDocument = false; _sb.Append( args.Message + Environment.NewLine ); } }

    Read the article

  • how to get response from remote server

    - by ruhit
    I have made a desktop application in asp.net using c# that connecting with remote server.I am able to connect but how do i show that my login is successful or not. After that i want to retrieve data from the remote server..........so plz help me.I have written the below code..............is there any better way try { string strId = UserId_TextBox.Text; string strpasswrd = Password_TextBox.Text; ASCIIEncoding encoding = new ASCIIEncoding(); string postData = "UM_email=" + strId; postData += ("&UM_password=" + strpasswrd); byte[] data = encoding.GetBytes(postData); MessageBox.Show(postData); // Prepare web request... //HttpWebRequest myRequest = (HttpWebRequest)WebRequest.Create("http://localhost/ruhit/basic_framework/index.php?menu=login=" + postData); HttpWebRequest myRequest =(HttpWebRequest)WebRequest.Create("http://www.facebook.com/login.php=" + postData); myRequest.Method = "POST"; myRequest.ContentType = "application/x-www-form-urlencoded"; myRequest.ContentLength = data.Length; Stream newStream = myRequest.GetRequestStream(); // Send the data. newStream.Write(data, 0, data.Length); MessageBox.Show("u r now connected"); HttpWebResponse response = (HttpWebResponse)myRequest.GetResponse(); // WebResponse response = myRequest.GetResponse(); StreamReader reader = new StreamReader(response.GetResponseStream()); string str = reader.ReadLine(); while (str != null) { str = reader.ReadLine(); MessageBox.Show(str); } reader.Close(); newStream.Close(); } catch { MessageBox.Show("error connecting"); }

    Read the article

  • Adding a Way To preserve A Comma In A CSV To DataTable Function

    - by Nick LaMarca
    I have a function that converts a .csv file to a datatable. One of the columns I am converting is is a field of names that have a comma in them i.e. "Doe, John" when converting the function treats this as 2 seperate fields because of the comma. I need the datatable to hold this as one field Doe, John in the datatable. Function CSV2DataTable(ByVal filename As String, ByVal sepChar As String) As DataTable Dim reader As System.IO.StreamReader Dim table As New DataTable Dim colAdded As Boolean = False Try ''# open a reader for the input file, and read line by line reader = New System.IO.StreamReader(filename) Do While reader.Peek() >= 0 ''# read a line and split it into tokens, divided by the specified ''# separators Dim tokens As String() = System.Text.RegularExpressions.Regex.Split _ (reader.ReadLine(), sepChar) ''# add the columns if this is the first line If Not colAdded Then For Each token As String In tokens table.Columns.Add(token) Next colAdded = True Else ''# create a new empty row Dim row As DataRow = table.NewRow() ''# fill the new row with the token extracted from the current ''# line For i As Integer = 0 To table.Columns.Count - 1 row(i) = tokens(i) Next ''# add the row to the DataTable table.Rows.Add(row) End If Loop Return table Finally If Not reader Is Nothing Then reader.Close() End Try End Function

    Read the article

  • Map inheritance from generic class in Linq To SQL

    - by Ksenia Mukhortova
    Hi everyone, I'm trying to map my inheritance hierarchy to DB using Linq to SQL: Inheritance is like this, classes are POCO, without any LINQ to SQL attributes: public interface IStage { ... } public abstract class SimpleStage<T> : IStage where T : Process { ... } public class ConcreteStage : SimpleStage<ConcreteProcess> { ... } Here is the mapping: <Database Name="NNN" xmlns="http://schemas.microsoft.com/linqtosql/mapping/2007"> <Table Name="dbo.Stage" Member="Stage"> <Type Name="BusinessLogic.Domain.IStage"> <Column Name="ID" Member="ID" DbType="Int NOT NULL IDENTITY" IsPrimaryKey="true" IsDbGenerated="true" AutoSync="OnInsert" /> <Column Name="StageType" Member="StageType" IsDiscriminator="true" /> <Type Name="BusinessLogic.Domain.SimpleStage" IsInheritanceDefault="true"> <Type Name="BusinessLogic.Domain.ConcreteStage" IsInheritanceDefault="true" InheritanceCode="1"/> </Type> </Type> </Table> </Database> In the runtime I get error: System.InvalidOperationException was unhandled Message="Mapping Problem: Cannot find runtime type for type mapping 'BusinessLogic.Domain.SimpleStage'." Neither specifying SimpleStage, nor SimpleStage<T> in mapping file helps - runtime keeps producing different types of errors. DC is created like this: StreamReader sr = new StreamReader(@"MappingFile.map"); XmlMappingSource mapping = XmlMappingSource.FromStream(sr.BaseStream); DataContext dc = new DataContext(@"connection string", mapping); If Linq to SQL doesn't support this, could you, please, advise some other ORM, which does. Thanks in advance, Regards! Ksenia

    Read the article

  • using ftpWebRequest with an error: the remote server returned error 530 not loged in

    - by user1361207
    I am trying to use the ftpWebRequest in c# my code is // Get the object used to communicate with the server. FtpWebRequest request = (FtpWebRequest)WebRequest.Create("ftp://192.168.20.10/file.txt"); request.Method = WebRequestMethods.Ftp.UploadFile; // This example assumes the FTP site uses anonymous logon. request.Credentials = new NetworkCredential("dev\ftp", "devftp"); // Copy the contents of the file to the request stream. StreamReader sourceStream = new StreamReader(@"\file.txt"); byte[] fileContents = Encoding.UTF8.GetBytes(sourceStream.ReadToEnd()); sourceStream.Close(); request.ContentLength = fileContents.Length; request.UsePassive = true; Stream requestStream = request.GetRequestStream(); requestStream.Write(fileContents, 0, fileContents.Length); requestStream.Close(); FtpWebResponse response = (FtpWebResponse)request.GetResponse(); Console.WriteLine("Upload File Complete, status {0}", response.StatusDescription); response.Close(); and I get an Error in request.GetRequestStream(); the error is: the remote server returned error 530 not loged in if I try to go in to a browser page and in the url I write ftp://192.168.20.10/ the brows page is asking me for a name and password, I put the same name and password and I see all the files and folders in the ftp folder. can any one help me with this problem?

    Read the article

  • How change encoding ?

    - by simply denis
    I need convert or set encoding windows-1251 Process p = new Process(); StreamWriter sw; StreamReader sr; StreamReader err; ProcessStartInfo psI = new ProcessStartInfo("cmd"); psI.UseShellExecute = false; psI.RedirectStandardInput = true; psI.RedirectStandardOutput = true; psI.RedirectStandardError = true; psI.CreateNoWindow = true; p.StartInfo = psI; p.Start(); sw = p.StandardInput; sr = p.StandardOutput; err = p.StandardError; sw.AutoFlush = true; if (tbComm.Text != "") sw.WriteLine(tbComm.Text); else //execute default command sw.WriteLine("dir \\"); sw.Close(); textBox1.Text = sr.ReadToEnd();// this not support russian word. I need convert or set encoding windows-1251 textBox1.Text += err.ReadToEnd();

    Read the article

  • Console.WriteLine does not show up in Output window

    - by Luke
    I have put some Console.WriteLine calls in to test, but they aren't appearing in the output box? public static ArrayList myDeliveries = new ArrayList(); public mainForm() { InitializeComponent(); } private void mainForm_Load(object sender, EventArgs e) { if (!File.Exists("../../MealDeliveries.txt")) { MessageBox.Show("File not found!"); return; } using (StreamReader sr = new StreamReader("../../MealDeliveries.txt")) { //first line is delivery name string strDeliveryName = sr.ReadLine(); Console.WriteLine("some tetttttttttt23423423423423423ttttttttttttttttttttttt"); while (strDeliveryName != null) { //other lines Delivery d = new Delivery(strDeliveryName, sr.ReadLine(), sr.ReadLine(), sr.ReadLine(), sr.ReadLine(), sr.ReadLine(), sr.ReadLine()); mainForm.myDeliveries.Add(d); //check for further values strDeliveryName = sr.ReadLine(); } } displayDeliveries(); } private void displayDeliveries() { lstDeliveryDetails.Items.Clear(); Console.WriteLine("some tettttttttttttttttttttttttttttttttt"); Console.WriteLine(mainForm.myDeliveries.Count); foreach (Delivery d in mainForm.myDeliveries) { lstDeliveryDetails.Items.Add(d.DeliveryName); } } Can anyone help??

    Read the article

  • How to strip out 0x0a special char from utf8 file using c# and keep file as utf8?

    - by user1013388
    The following is a line from a UTF-8 file from which I am trying to remove the special char (0X0A), which shows up as a black diamond with a question mark below: 2464577 ????? True s6620178 Unspecified <1?1009-672 This is generated when SSIS reads a SQL table then writes out, using a flat file mgr set to code page 65001. When I open the file up in Notepad++, displays as 0X0A. I'm looking for some C# code to definitely strip that char out and replace it with either nothing or a blank space. Here's what I have tried: string fileLocation = "c:\\MyFile.txt"; var content = string.Empty; using (StreamReader reader = new System.IO.StreamReader(fileLocation)) { content = reader.ReadToEnd(); reader.Close(); } content = content.Replace('\u00A0', ' '); //also tried: content.Replace((char)0X0A, ' '); //also tried: content.Replace((char)0X0A, ''); //also tried: content.Replace((char)0X0A, (char)'\0'); Encoding encoding = Encoding.UTF8; using (FileStream stream = new FileStream(fileLocation, FileMode.Create)) { using (BinaryWriter writer = new BinaryWriter(stream, encoding)) { writer.Write(encoding.GetPreamble()); //This is for writing the BOM writer.Write(content); } } I also tried this code to get the actual string value: byte[] bytes = { 0x0A }; string text = Encoding.UTF8.GetString(bytes); And it comes back as "\n". So in the code above I also tried replacing "\n" with " ", both in double quotes and single quotes, but still no change. At this point I'm out of ideas. Anyone got any advice? Thanks.

    Read the article

  • Read huge free text docs in one file for lucene indexing

    - by Jun
    I have heaps of free text news docs in one big file. The structure of each news doc is like: (Header line) Category, Doc1, Date (day, month, year) (body text) ... ... ... (Header line) Category, Doc2, Date (day, month, year) (body text) ... ... ... If I extract each doc from the big file, it costs too much time and not efficient. Therefore, I decide to read the file line by line and feed information to lucene the same time. I write c# code to index each doc to lucene like: Streamreader sr = new Streamreader(file); string line = ""; while((line = sr.ReadLine()) != null) { How can I tell this line is a doc header line from text line and get the metadata and all the text lines of a doc for lucene to index. Also, the text is read by OCR which can not give correct line-separating. Captions are mixed with content text iterate the process till the end of the file } with thanks

    Read the article

  • Help me convert C# 1.1 Xml validation code to C# 2.0 please.

    - by Hamish Grubijan
    It would be fantastic if you could help me rid of these warnings below. I have not been able to find a good document. Since the warnings are concentrated in just the private void ValidateConfiguration( XmlNode section ) section, hopefully this is not terribly hard to answer, if you have encountered this before. Thanks! 'System.Configuration.ConfigurationException.ConfigurationException(string)' is obsolete: 'This class is obsolete, to create a new exception create a System.Configuration!System.Configuration.ConfigurationErrorsException' 'System.Xml.XmlValidatingReader' is obsolete: 'Use XmlReader created by XmlReader.Create() method using appropriate XmlReaderSettings instead. http://go.microsoft.com/fwlink/?linkid=14202' private void ValidateConfiguration( XmlNode section ) { // throw if there is no configuration node. if( null == section ) { throw new ConfigurationException("The configuration section passed within the ... class was null ... there must be a configuration file defined.", section ); } //Validate the document using a schema XmlValidatingReader vreader = new XmlValidatingReader( new XmlTextReader( new StringReader( section.OuterXml ) ) ); // open stream on Resources; the XSD is set as an "embedded resource" so Resource can open a stream on it using (Stream xsdFile = XYZ.GetStream("ABC.xsd")) using (StreamReader sr = new StreamReader(xsdFile)) { vreader.ValidationEventHandler += new ValidationEventHandler(ValidationCallBack); vreader.Schemas.Add(XmlSchema.Read(new XmlTextReader(sr), null)); vreader.ValidationType = ValidationType.Schema; // Validate the document while (vreader.Read()) { } if (!_isValidDocument) { _schemaErrors = _sb.ToString(); throw new ConfigurationException("XML Document not valid"); } } } // Does not cause warnings. private void ValidationCallBack( object sender, ValidationEventArgs args ) { // check what KIND of problem the schema validation reader has; // on FX 1.0, it gives a warning for "<xs:any...skip" sections. Don't worry about those, only set validation false // for real errors if( args.Severity == XmlSeverityType.Error ) { _isValidDocument = false; _sb.Append( args.Message + Environment.NewLine ); } }

    Read the article

  • How do I make a lock that allows only ONE thread to read from the resource ?

    - by mare
    I have a file that holds an integer ID value. Currently reading the file is protected with ReaderWriterLockSlim as such: public int GetId() { _fileLock.EnterUpgradeableReadLock(); int id = 0; try { if(!File.Exists(_filePath)) CreateIdentityFile(); FileStream readStream = new FileStream(_filePath, FileMode.Open, FileAccess.Read); StreamReader sr = new StreamReader(readStream); string line = sr.ReadLine(); sr.Close(); readStream.Close(); id = int.Parse(line); return int.Parse(line); } finally { SaveNextId(id); // increment the id _fileLock.ExitUpgradeableReadLock(); } } The problem is that subsequent actions after GetId() might fail. As you can see the GetId() method increments the ID every single time, disregarding what happens after it has issued an ID. The issued ID might be left hanging (as said, exceptions might occur). As the ID is incremented, some IDs might be left unused. So I was thinking of moving the SaveNextId(id) out, remove it (the SaveNextId() actually uses the lock too, except that it's EnterWriteLock). And call it manually from outside after all the required methods have executed. That brings out another problem - multiple threads might enter the GetId() method before the SaveNextId() gets executed and they might all receive the same ID. I don't want any solutions where I have to alter the IDs after the operation, correcting them in any way because that's not nice and might lead to more problems. I need a solution where I can somehow callback into the FileIdentityManager (that's the class that handles these IDs) and let the manager know that it can perform the saving of the next ID and then release the read lock on the file containing the ID. Essentialy I want to replicate the relational databases autoincrement behaviour - if anything goes wrong during row insertion, the ID is not used, it is still available for use but it also never happens that the same ID is issued. Hopefully the question is understandable enough for you to provide some solutions..

    Read the article

  • How to put data from List<string []> to dataGridView

    - by Kirill
    Try to put some data from List to dataGridView, but have some problem with it. Currently have method, that return me required List - please see picture below code public List<string[]> ReadFromFileBooks() { List<string> myIdCollection = new List<string>(); List<string[]> resultColl = new List<string[]>(); if (chooise == "all") { if (File.Exists(filePath)) { using (FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read)) { StreamReader sr = new StreamReader(fs); string[] line = sr.ReadToEnd().Split(new string[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries); foreach (string l in line) { string[] result = l.Split(','); foreach (string element in result) { myIdCollection.Add(element); } resultColl.Add(new string[] { myIdCollection[0], myIdCollection[1], myIdCollection[2], myIdCollection[3] }); myIdCollection.Clear(); } sr.Close(); return resultColl; } } .... this return to me required data in requred form (like list from arrays). After this, try to move it to the dataGridView, that already have 4 columns with names (because i'm sure, that no than 4 colums required) - please see pic below Try to put data in to dataGridView using next code private void radioButtonViewAll_CheckedChanged(object sender, EventArgs e) { TxtLibrary myList = new TxtLibrary(filePathBooks); myList.chooise = "all"; //myList.ReadFromFileBooks(); DataTable table = new DataTable(); foreach (var array in myList.ReadFromFileBooks()) { table.Rows.Add(array); } dataGridViewLibrary.DataSource = table; } But as result got error - "required more rows that exist in dataGridVIew", but accordint to what I'm see (pic above) q-ty of rows (4) equal q-ty of arrays element in List (4). Try to check result by putting additional temp variables - but it's ok - please see pic below Where I'm wrong? Maybe i use dataGridView not in correct way?

    Read the article

  • C#, How to download file into string with progress callback?

    - by Kaminari
    I would like to use the WebClient (or there is another better option?) but there is a problem. I understand that opening up the stream takes some time and this can not be avoided. However, reading it takes a strangely much more amount of time compared to read it entirely immediately. Of course it's not working good because i'm not so familiar with streams. Is there a best way to do this? I mean two ways, to string and to file. Progress is my own delegate and it's working good. FIRST UPDATE: Ok, now i got something like this and it seems to work but still slow: System.Net.WebClient client = new System.Net.WebClient(); System.IO.Stream streamRemote = client.OpenRead(new Uri(URL)); if (savePath == null) { StreamReader reader = new StreamReader(streamRemote); int iByteSize = 0; byte[] byteBuffer = new byte[iSize]; char[] charBuffer = new char[iSize]; StringBuilder sb = new StringBuilder(); while ((iByteSize = reader.Read(charBuffer, 0, iSize)) > 0) { sb.Append(charBuffer, 0, iByteSize); iRunningByteTotal += iByteSize; float dIndex = (float)(iRunningByteTotal); float dTotal = (float)byteBuffer.Length; float dProgressPercentage = (dIndex / dTotal); float iProgressPercentage = (dProgressPercentage * 100); if (Progress != null) Progress(iProgressPercentage); } result = sb.ToString(); } Im wondering about DownloadStringAsync method?

    Read the article

  • read line by line the text file for make map in xna

    - by Mohammadali Najjar khodabakhsh
    i want to read a text file for build map; for example I have this map 0@0000000 0@0000000 0@0000000 000000000 000000000 000000000 000000000 I know I should use this : StreamReader reader = new StreamReader(Application.StartupPath+@"/TestMap.MMAP"); string line = reader.ReadToEnd(); reader.Close(); now for example I want read line 2 char "@". how can i do this? please help me. solve : Thank you (L.B AND user861114) at last my problem solve like this : string[,] item = new string[9, 7]; string[] line = File.ReadAllLines(Application.StartupPath + @"/TestMap.MMAP"); for (int j = 0; j < 7; j++) { for (int i = 0; i < 9; i++) { item[i, j] = line[j].Substring(i, 1); Console.WriteLine(i + " " + j + "=" + item[i, j]); } } thanks alot.

    Read the article

< Previous Page | 6 7 8 9 10 11 12 13 14 15 16 17  | Next Page >