Increment file everytime script is called C# - 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";

Related

Out of memory in LineReader

I am making a program that reads a .tyd file and tries to translate all the text between the " from English to Italian.
GoToDesk translate-> "Looking for computer"
The problem is that I am still getting "Out of memory".
The code is:
using System.Collections;
using System.Net;
using MiscUtil.IO;
namespace Soft_inc
{
class MyProject
{
public static string TranslateText(string input, string languagePair)
{
string url = String.Format("http://translate.google.it/?hl=en&ie=UTF8&text={0}&langpair={1}", input, languagePair);
WebClient webClient = new WebClient();
webClient.Encoding = System.Text.Encoding.UTF8;
string result = webClient.DownloadString(url);
result = result.Substring(result.IndexOf("<span title=\"") + "<span title=\"".Length);
result = result.Substring(result.IndexOf(">") + 1);
result = result.Substring(0, result.IndexOf("</span>"));
return result.Trim();
}
public static void Main()
{
string path_file = #"H:\Games\Software.In.v11.7.62\Software.In.v11.7.62\Localization\Italiano\idk\UI.tyd";
string Ftext = System.IO.File.ReadAllText(path_file);
ArrayList ar = new ArrayList();
Console.WriteLine("This may require some time.");
foreach (string line in new LineReader(() => new StringReader(Ftext)))
{
if(line.IndexOf("\"") == -1) continue;
string text = line.Substring(line.IndexOf("\""));
text = text.Replace("\"","");
if(text.Length == 0) continue;
ar.Add(text);
}
int idk = 0;
while(true)
{
idk++;
if(idk == ar.Count) break;
string oldT = (string)ar[idk];
Ftext = Ftext.Replace(oldT, TranslateText(oldT,"en|it"));
}
System.IO.File.WriteAllText("UI.tyd",Ftext);
}
}
}
Maybe it is because the file has 2535 lines of text?
How I can fix this?
You need to use StreamReader class. It is not necessary to read all file content into RAM. Open one StreamReader and one StreamWriter. Reed file line by line and write translated data into a temporary file. When all content is translated just move temp file to needed destination. Don't forget to close source and destination handles before moving.

Create a new .txt file instead of appending in C# [duplicate]

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();
}
}

How do I code my program to create new file name for every new file in a directory?

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.

Matching the name and size of a file

I'm having some trouble integrating two pieces of code. The first checks the size of a file and the next one loops trough a SQL database and looks for a matching name for a file. I basically want to check if it's a new file or if the file has changed since I logged some of it's data last time.
This gets the size of each file in the directory
// Make a reference to a directory.
DirectoryInfo di = new DirectoryInfo("C:\\Users");
// Get a reference to each file in that directory.
FileInfo[] fiArr = di.GetFiles();
// Display the names and sizes of the files.
MessageBox.Show("The directory {0} contains the following files:", di.Name);
foreach (FileInfo f in fiArr)
MessageBox.Show("The size of" + f.Name + " is " + f.Length + " bytes.");
This code loops untill it finds a mach or untill all entries has been looked trough.
try
{
// LINQ query for all files containing the word '.txt'.
var files = from file in
Directory.EnumerateFiles("C:\\Users")
where file.ToLower().Contains(".txt")
select file;
foreach (var file in files)
{
//Get path to HH file
filename = System.IO.Path.GetFileName(file);
tempString = "";
//Keep looking trough database utill database empty or HH found
while (inc != numberOfSessions && (filename != tempString))
{
sessionRow = sessions.Tables["Sessions"].Rows[inc];
tempString = sessionRow.ItemArray.GetValue(1).ToString();
inc++;
}
Lets say ItemAttay.GetValue(2) returns the saved size of a file. How can i most efficiently keep the while loop going if
inc != numberOfSessions && (filename != tempString) && (sessionRow.ItemArray.GetValue(2) == f.length)
Thanks for having a look!
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Data;
class Program
{
static void Main(string[] args)
{
var files1 = new List<string>(Directory.GetFiles(args[0],
"*.txt",
SearchOption.AllDirectories));
List<FileData> ListFiles = new List<FileData>();
for (int i = 0; i < files1.Count; i++)
{
FileInfo file = new FileInfo(files1[i]);
FileData _tmpfile = new FileData(file.Name.ToString(), file.Length,
File.GetLastWriteTime(files1[1]).ToString("yyyy-MM-dd H:mm:ss"),
File.GetLastAccessTime(files1[1]).ToString("yyyy-MM-dd H:mm:ss"));
ListFiles.Add(_tmpfile);
}
DataSet sessions = new DataSet();
DataTable dt = sessions.Tables["Sessions"];
for (int i = 0; i < ListFiles.Count; i++)
{
//compares every file in folder to database
FileData _tmp = ListFiles[i];
for (int j = 0; j < dt.Rows.Count; j++)
{
if (_tmp.GSFileName == dt.Rows[i][0].ToString())
{
//put some code here
break;
}
if (_tmp.GSSize == long.Parse(dt.Rows[i][1].ToString()))
{
//put some code here
break;
}
}
}
}
}
public class FileData
{
string FileName = "";
public string GSFileName
{
get { return FileName; }
set { FileName = value; }
}
long Size = 0;
public long GSSize
{
get { return Size; }
set { Size = value; }
}
string DateOfModification = "";
public string GSDateOfModification
{
get { return DateOfModification; }
set { DateOfModification = value; }
}
string DateOfLastAccess = "";
public string GSDateOfLastAccess
{
get { return DateOfLastAccess; }
set { DateOfLastAccess = value; }
}
public FileData(string fn, long si, string dateofmod, string dateofacc)
{
FileName = fn;
Size = si;
DateOfModification = dateofmod;
DateOfLastAccess = dateofacc;
}
}

How to Access Variable From One Class in Another Class? [C#]

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

Categories

Resources