Create a new .txt file instead of appending in C# [duplicate] - c#
This question already has answers here:
C# File Naming Incremented Name 001++
(3 answers)
Automatically rename a file if it already exists in Windows way
(10 answers)
File name with prefix and number
(2 answers)
How to create consecutive named files
(1 answer)
Closed 2 years ago.
my serial port stream prints 10 lines of data and then pauses, right now I have it running on loop so when I close the stream my .txt files looks like this:
8205,17.51,150.45,-31.27,-170.05,27.01,160.82,20.90,140.70,9.04,160.07
8283,17.11,149.94,-28.36,-173.83,26.96,158.14,20.59,139.33,9.81,163.18
8360,16.83,149.43,-25.49,-177.23,26.93,155.32,20.23,137.91,10.31,165.87
8438,16.54,148.91,-22.70,179.71,26.95,152.43,19.87,136.46,10.55,168.05
8516,16.25,148.41,-20.05,176.97,27.03,149.46,19.53,134.96,10.62,169.77
8594,15.71,147.75,-17.63,174.62,26.95,146.57,19.11,133.39,10.54,171.02
8672,15.40,147.20,-15.38,172.53,26.92,143.51,18.69,131.79,10.40,172.02
8750,14.97,146.59,-13.37,170.74,27.12,140.25,18.25,130.16,10.22,172.67
8827,14.51,145.95,-11.67,169.22,27.06,137.08,17.78,128.44,10.06,173.09
8905,14.18,145.33,-10.20,168.01,27.04,133.74,17.29,126.68,9.92,173.41
10373,5.38,128.09,-4.03,163.82,12.60,58.36,3.28,81.27,9.29,173.94
10450,4.90,126.76,-4.03,163.87,11.06,58.47,2.17,77.95,9.32,173.97
10528,4.41,125.37,-4.04,163.89,11.26,58.00,0.99,74.50,9.29,173.94
10605,3.95,123.91,-4.03,163.87,11.21,58.24,-0.25,70.91,9.29,173.89
10683,3.51,122.40,-4.06,163.88,11.88,58.18,-1.56,67.21,9.28,173.87
10760,3.10,120.81,-4.05,163.88,11.69,58.15,-2.94,63.38,9.32,173.93
10838,2.65,119.18,-4.05,163.87,10.90,58.80,-4.43,59.36,9.34,173.95
10915,2.25,117.48,-4.07,163.90,10.59,58.80,-6.03,55.20,9.37,173.93
10992,1.84,115.70,-4.09,163.96,11.04,58.75,-7.78,50.88,9.39,173.95
11070,1.45,113.87,-4.08,163.97,11.54,58.72,-9.65,46.35,9.37,173.94
11147,1.40,113.60,-4.07,163.97,10.89,59.06,-11.14,43.04,9.38,173.98
11225,1.08,111.68,-4.11,164.01,11.78,58.57,-13.41,38.18,9.39,174.02
11302,0.72,109.66,-4.11,164.03,12.08,58.60,-15.97,33.17,9.37,174.00
11379,0.38,107.58,-4.11,164.01,11.28,59.05,-18.44,28.89,9.35,173.95
11457,0.11,105.39,-4.10,164.06,10.20,59.66,-18.48,29.09,9.37,174.00
11535,-0.16,103.13,-4.12,164.12,10.37,59.57,-18.00,29.31,9.41,173.98
11613,-0.38,100.75,-4.13,164.14,10.58,59.73,-18.61,29.05,9.41,174.04
.
.
.
.
.
.
What i'm trying to do is instead of appending in the same file. I'm trying to create a new file that's incremental in numbering.
for e.g txt01,txt02,txt03.....txtn.
can anyone help me with this
using UnityEngine;
using System;
using System.Collections;
using System.IO.Ports;
using System.IO;
public class ArduinoControl : MonoBehaviour
{
public string portName = "COM5";
public string receivedstring;
SerialPort arduino;
void Start()
{
arduino = new SerialPort(portName, 115200);
arduino.Open();
}
void Update()
{
if (arduino.IsOpen)
{
arduino.Write("s");
receivedstring = arduino.ReadLine();
WriteOutputToTextFile(receivedstring); // Write to csv here...
arduino.BaseStream.Flush();
}
}
static void WriteOutputToTextFile(string _data)
{
string FolderName = Environment.GetFolderPath(Environment.SpecialFolder.Desktop); //set destination as your desktop
using (StreamWriter SW = new StreamWriter(FolderName + "\\test.txt", true)) //true makes it append to the file instead of overwrite
{
SW.WriteLine(_data);
SW.Close();
}
}
}
You can use this
void Start()
{
receivedstring= string.Empty;
arduino = new SerialPort(portName, 115200);
arduino.Open();
}
private static int counter;
static void WriteOutputToTextFile(string _data)
{
string FolderName = Environment.GetFolderPath(Environment.SpecialFolder.Desktop); //set destination as your desktop
using (StreamWriter SW = new StreamWriter(${FolderName}\\test{counter}.txt", false))
{
SW.WriteLine(_data);
SW.Close();
}
counter++;
lineCount=0;
receivedstring= string.Empty;
}
private static int lineCount;
void Update()
{
if (arduino.IsOpen)
{
arduino.Write("s");
receivedstring += arduino.ReadLine() + "\r\n";
lineCont++;
If(lineCount >=10 && !string.IsNullOrEmpty (receivestring))
WriteOutputToTextFile(receivedstring); // Write to csv here...
arduino.BaseStream.Flush();
}
}
Related
Increment file everytime script is called C#
I am calling this script from a unity project. At this point what I am trying to do is increment the file every time the script is called. So once it is called it reads the data saves the data in a file. Right now it only makes a file alpha0.csv and doesn't print a new file if I call the script again. Can anyone guide me on how to fix this issue. using UnityEngine; using System; using System.Collections; using System.IO.Ports; using System.IO; using System.Management; using Microsoft.Win32; using System.Collections.Generic; public class ArduinoControl : MonoBehaviour { SerialPort arduino; public string portName = "COM5"; public static bool status ; public string test = "alpha"; private static int counter; private static int lineCount; private static string receivedstring = string.Empty; void Start() { arduino = new SerialPort(portName, 115200); arduino.Open(); status = true; } void Update() { if (arduino.IsOpen) { if (status) // (& UnityCommand = "F") { arduino.Write("s"); arduino.ReadTimeout = 5000; arduino.WriteTimeout = 5000; receivedstring += arduino.ReadLine() + "\r\n"; arduino.BaseStream.Flush(); lineCount++; if(lineCount >= 10 && receivedstring != null) { WriteOutputToTextFile(test,receivedstring); // Write to csv here... status = false; } arduino.BaseStream.Flush(); } } } //private static int counter; static void WriteOutputToTextFile(string path,string _data) { string FolderName = Environment.GetFolderPath(Environment.SpecialFolder.Desktop); //set destination as your desktop using (StreamWriter SW = new StreamWriter($"{FolderName }\\{path}{counter}.csv", false)) { SW.WriteLine(_data); SW.Close(); } counter++; lineCount = 0; receivedstring = string.Empty; } }
If i understand correctly you want to create a new file with the correct numerical suffix, as in alpha0.csv, alpha1.csv, alpha2.csv... This can actually be a bit of a pain to do, you could use a variable in a wider scope as comments suggest but as you are saving this to disk I assume you want this to work correctly even between starting and stopping your program. I would suggest Make sure all your files are in their own folder Read in all of the file names Run a 'find max' algorithm on the suffixes in your folder Add 1 to this and use that to create your new file Reading in file names can be done in Unity like so: DirectoryInfo dir = new DirectoryInfo("/*your directory*/"); FileInfo[] fileInfos = dir.GetFiles("*.csv"); Then for getting the next suffix static readonly string rootName = "Alpha"; int maxFileNumber = 0; foreach (var f in fileInfos) { string tempName = f.Name; tempName = tempName.Substring(0, tempName.Length - ".csv".Length); // remove .csv int lengthOfNumber = tempName.Length - rootName.Length; // get the length of the number at the end of the name nextFileNumber = int.Parse(tempName.Substring(rootName.Length, lengthOfNumber)); // get the number at the end of the name maxFileNumber = nextFileNumber > maxFileNumber ? nextRoomNumber : maxRoomNumber; // find max alorithm } nextFileNumber += 1; // next number string newFileName = rootName + ToString(nextFileNumber)+".csv";
How I can access a file with c#? [duplicate]
This question already has answers here: How to read an entire file to a string using C#? (17 answers) Closed 3 years ago. There are some function that read all text from file without use FileStream class and more easy? In microsoft doc found this code to read from file but I think is some complexed. private async void Button_Click_1(object sender, RoutedEventArgs e) { string filename = #"C:\Example\existingfile.txt"; char[] result; StringBuilder builder = new StringBuilder(); using (StreamReader reader = File.OpenText(filename)) { result = new char[reader.BaseStream.Length]; await reader.ReadAsync(result, 0, (int)reader.BaseStream.Length); } foreach (char c in result) { if (char.IsLetterOrDigit(c) || char.IsWhiteSpace(c)) { builder.Append(c); } } FileOutput.Text = builder.ToString(); }
Please see the File.ReadAllText Method. public static void Main() { string path = #"c:\temp\MyTest.txt"; // This text is added only once to the file. if (!File.Exists(path)) { // Create a file to write to. string createText = "Hello and Welcome" + Environment.NewLine; File.WriteAllText(path, createText, Encoding.UTF8); } // This text is always added, making the file longer over time // if it is not deleted. string appendText = "This is extra text" + Environment.NewLine; File.AppendAllText(path, appendText, Encoding.UTF8); // Open the file to read from. string readText = File.ReadAllText(path); Console.WriteLine(readText); }
Counting the # of lines in a very large file gives System OutofMemory Exception [duplicate]
This question already has answers here: What's the fastest way to read a text file line-by-line? (9 answers) Closed 5 years ago. static void Main(string[] args) { string TheDataFile = ""; string ErrorMsg = ""; string lngTransDate = ""; ProcessDataFile ProcessTheDataFile = new ProcessDataFile(); string TheFile = "S:\\MIS\\Provider NPI file\\Processed\\npidata_20050523-20161009.csv"; string[] lines = File.ReadAllLines(TheFile, Encoding.UTF8);//Read all lines to an array Console.WriteLine(lines.Length.ToString()); Console.ReadLine(); } This throws an error because the file is very large (has 6 million lines). Is there a way to handle large files and count the # of lines?
Use a StreamReader: string TheFile = "S:\\MIS\\Provider NPI file\\Processed\\npidata_20050523-20161009.csv"; int count = 0; using (System.IO.StreamReader sr = new System.IO.StreamReader(TheFile)) { while (sr.ReadLine() != null) count++; }
You need to do a lazy evaluation of the file so it isn't loaded into memory entirelly. Helper method public static class ToolsEx { public static IEnumerable<string> ReadAsLines(this string filename) { using (var streamReader = new StreamReader(filename)) while (!streamReader.EndOfStream) yield return streamReader.ReadLine(); } } Usage var lineCount = "yourfile.txt".ReadAsLines().Count();
According to this already accepted answer, this should do it. using System; using System.IO; namespace CountLinesInFiles_45194927 { class Program { static void Main(string[] args) { int counter = 0; foreach (var line in File.ReadLines("c:\\Path\\To\\File.whatever")) { counter++; } Console.WriteLine(counter); Console.ReadLine(); } } }
How can i split a text file in many files but the separation would be a specific string? [closed]
Closed. This question needs details or clarity. It is not currently accepting answers. Want to improve this question? Add details and clarify the problem by editing this post. Closed 8 years ago. Improve this question I´m trying to split a big text file in many files, but each 600-700-900 lines (could be less or more) I have a string that says "Finished File", how can I do it using C#?
Here's an example that should work for you. using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.IO; namespace ConsoleApplicationExample { class Program { static void Main(string[] args) { Runner r = new Runner(); r.SplitFile(#"C:\path\to\my\file.txt"); } } public class Runner { private readonly string m_delimiter; public Runner() { m_delimiter = "Finished File"; } public void SplitFile(string inputFile) { try { StreamReader reader = new StreamReader(inputFile); StreamWriter writer; int i = 1; // count up for every output file, auto-numbering from 1 string line; do { string outputFile = GenerateFileName(inputFile, i); writer = new StreamWriter(outputFile); while ((line = reader.ReadLine()) != null) { if (line.CompareTo(m_delimiter) == 0) { writer.Close(); break; // breaking will exit the while-loop & increment i to build a new output file name } else writer.WriteLine(line); } i++; } while (line != null); writer.Close(); } catch (Exception ex) { Console.WriteLine("Error splitting file: " + ex.ToString()); } } private string GenerateFileName(string inputFile, int i) { string folder = Path.GetFullPath(inputFile); string fileNameNoExt = Path.GetFileNameWithoutExtension(inputFile); string ext = Path.GetExtension(inputFile); return folder + fileNameNoExt + "." + i.ToString("000") + ext; // zero-pads "000" } } }
Unable to open CSV file from website [duplicate]
This question already has answers here: Closed 11 years ago. Possible Duplicate: Unable to open CSV file from internet using C# I wrote this code to open and parse a CSV file. It works when I open the file from a folder on my hard drive. I changed the code on lines 24 - 26 to open the file from a website. I'm getting the error message "URI formats are not supported" from Line 27 of attached code. I can open the file using VBA. using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.IO; using System.Net; namespace ConsoleApplication1 { class Program { static void Main(string[] args) { // // Read in a file line-by-line, and store it all in a List. // int i = 0; DateTime dte; List<string> list = new List<string>(); float[] Prices = new float[4]; WebClient wc = new WebClient(); byte[] data = wc.DownloadData("http://www.datasource.com/apps/qt/csv/pricehistory.ac?section=yearly_price_download&code=XXX"); using (StreamReader reader = new StreamReader(wc)) { string line; while ((line = reader.ReadLine()) != null) { //list.Add(line); // Add to list. Console.WriteLine(line); // Write to console. string[] parts = line.Split(','); int DateSetter = 1; int DateDone = 0; int CountFloat = 0; int PricesDone = 0; Double Volume = 0; foreach (string part in parts) { Console.WriteLine("{0} : {1}", i, part); if (DateSetter == 1) { dte = DateTime.Parse(part); DateSetter = 2; Console.WriteLine(dte); } if (DateDone == 1) { if (DateSetter < 6) { Prices[CountFloat] = float.Parse(part); CountFloat++; DateSetter++; Console.WriteLine(Prices[3]); } } DateDone = 1; if (PricesDone == 1) { Volume = double.Parse(part); Console.WriteLine(Volume); } if (DateSetter == 6) { PricesDone = 1; } } } } Console.ReadLine(); } } }
You can just replace byte[] data = wc.DownloadData With String data = wc.DownloadString In case your request is not really big. And this will simplify all program.