Matching the name and size of a file - c#

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

Related

Need help to develop a C# code to put the header validation

I have a flat file with comma separated values which need to be transfer to a datatable and the values on the first line is header name, will be used as columns name of the datatable. But Before that, I need to check if all required header (Some Mandatory headers) are available in the flat file. Please help me to develop a C# code to put the header validation.
`.
.
.
/getting full file path of Uploaded file and read all text
System.IO.StreamReader file = new System.IO.StreamReader(#path);
string line;
while ((line = file.ReadLine()) != null)
{
string[] linetemp = line.Split(new char[] { ',' });
if(tblcsv.Rows.Count==0)
{
foreach (string ColName in linetemp)
{
tblcsv.Columns.Add(ColName); //Creating columns with available headers names
}
}
tblcsv.Rows.Add();
.
.
.
`//remaining code
For example
If the flat file will contain
datetime,status,Assignee,Reporter,Duration,Col1,Col2,Remarks
1504451523568,Inprogress,ABC,BCD,120,True,B,comments...
1504451523567,Completed,DFG,BCD,120,True,B,comments...
1504451523566,unassigned,VNB,BCD,160,,B,comments...
1504451523565,Inprogress,ERT,FGH,150,True,,comments...
and I need to check that only First line have all mandaory header(like- datetime,Status,Assignee and Duration).
I tired to implement your particular requirement with a sample Csv file from online. Csv file can be found here, I may not have a sophisticated code, but tried to take a simplest way to solve this particular problem.
Below is the short version of code which is of your importance.
String firstLine;
var fileStream = new FileStream( # "C:\Users\user\Desktop\AssetsImportCompleteSample.csv", FileMode.Open,
FileAccess.Read);
using(var streamReader = new StreamReader(fileStream, Encoding.UTF8)) {
firstLine = streamReader.ReadLine();
}
var values = firstLine.Split(',');
for (int i = 0; i < values.Length; i++) {
values[i] = values[i].Trim();
}
if (values.Length == 4)
{
int count=0;
IList<string> newList = new List<string> { "MXASSETInterface", "SRM_SaaS_ES", "EN", "AddChange" };
for (int i = 0; i < values.Length; i++)
{
if (newList.Contains(values[i]))
{
count++;
newList.Remove(values[i]);
}
}
if (count == 4)
{
Console.WriteLine("head is correct");
}
else
{
Console.WriteLine("head is incorrect");
}
}
The complete console application can be found with below code, which can be run direct
class Program
{
static void Main(string[] args)
{
try
{
String firstLine;
var fileStream = new FileStream(#"C:\Users\user\Desktop\AssetsImportCompleteSample.csv", FileMode.Open,
FileAccess.Read);
using (var streamReader = new StreamReader(fileStream, Encoding.UTF8))
{
firstLine = streamReader.ReadLine();
}
if (firstLine != null)
{
var values = firstLine.Split(',');
Console.WriteLine(firstLine);
for (int i = 0; i < values.Length; i++)
{
values[i] = values[i].Trim();
Console.WriteLine(values[i]);
}
if (values.Length == 4)
{
int count=0;
IList<string> newList = new List<string> { "MXASSETInterface", "SRM_SaaS_ES", "EN", "AddChange" };
for (int i = 0; i < values.Length; i++)
{
if (newList.Contains(values[i]))
{
count++;
newList.Remove(values[i]);
}
}
if (count == 4)
{
Console.WriteLine("head is correct");
}
else
{
Console.WriteLine("head is incorrect");
}
}
else
{
Console.WriteLine("header is Invalid");
}
}
else
{
Console.WriteLine("header is Invalid");
}
Console.ReadLine();
}
catch (Exception e)
{
Console.WriteLine("Please check if file is available or path is correct", e.Message);
}
Console.ReadLine();
}
}
I suggest using CsvHelpet library for parsing the CSV file. It allows to define a class that represents a row in your file. Header names are property names by default or they can be mapped usimg fluent API.
var csv = new CsvReader( textReader ); var records = csv.GetRecords();
Get records will fail if some headers are missing.

StreamWriter: Starting and ending on a specific line number

I would like to ask some tips and help on a reading/writing part of my C#.
Situation:
I have to read a CSV file; - OK
If the CSV file name starts with "Load_", I want to write on another CSV the data from line 2 to the last one;
If the CSV file name starts with "RO_", I want to write on 2 different CSVs, 1 with the line 1 to 4 and the other 4 to the last one;
What I have so far is:
public static void ProcessFile(string[] ProcessFile)
{
// Keeps track of your current position within a record
int wCurrLine = 0;
// Number of rows in the file that constitute a record
const int LINES_PER_ROW = 1;
int ctr = 0;
foreach (string filename in ProcessFile)
{
var sbText = new System.Text.StringBuilder(100000);
int stop_line = 0;
int start_line = 0;
// Used for the output name of the file
var dir = Path.GetDirectoryName(filename);
var fileName = Path.GetFileNameWithoutExtension(filename);
var ext = Path.GetExtension(filename);
var folderbefore = Path.GetFullPath(Path.Combine(dir, #"..\"));
var lineCount = File.ReadAllLines(#filename).Length;
string outputname = folderbefore + "output\\" + fileName;
using (StreamReader Reader = new StreamReader(#filename))
{
if (filename.Contains("RO_"))
{
start_line = 1;
stop_line = 5;
}
else
{
start_line = 2;
stop_line = lineCount;
}
ctr = 0;
while (!Reader.EndOfStream && ctr < stop_line)
{
// Add the text
sbText.Append(Reader.ReadLine());
// Increment our current record row counter
wCurrLine++;
// If we have read all of the rows for this record
if (wCurrLine == LINES_PER_ROW)
{
// Add a line to our buffer
sbText.AppendLine();
// And reset our record row count
wCurrLine = 0;
}
ctr++;
} // end of the while
}
int total_lenght = sbText.Length
// When all of the data has been loaded, write it to the text box in one fell swoop
using (StreamWriter Writer = new StreamWriter(dir + "\\" + "output\\" + fileName + "_out" + ext))
{
Writer.Write.(sbText.);
}
} // end of the foreach
} // end of ProcessFile
I was thinking about using the IF/ELSE: "using (StreamWriter Writer = new StreamWriter(dir + "\" + "output\" + fileName + "_out" + ext))" part. However, I am not sure how to pass, to StreamWriter, to only write from/to a specific line number.
Any Help is welcome! If I am missing some information, please, let me know (I am pretty new on stackoverflow).
Thank you.
Code is way too complicated
using System.Collections.ObjectModel;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
namespace ConsoleApplication57
{
class Program
{
static void Main(string[] args)
{
}
public static void ProcessFile(string[] ProcessFile)
{
foreach (string filename in ProcessFile)
{
// Used for the output name of the file
var dir = Path.GetDirectoryName(filename);
var fileName = Path.GetFileNameWithoutExtension(filename);
var ext = Path.GetExtension(filename);
var folderbefore = Path.GetFullPath(Path.Combine(dir, #"..\"));
var lineCount = File.ReadAllLines(#filename).Length;
string outputname = folderbefore + "output\\" + fileName;
using (StreamWriter Writer = new StreamWriter(dir + "\\" + "output\\" + fileName + "_out" + ext))
{
int rowCount = 0;
using (StreamReader Reader = new StreamReader(#filename))
{
rowCount++;
string inputLine = "";
while ((inputLine = Reader.ReadLine()) != null)
{
if (filename.Contains("RO_"))
{
if (rowCount <= 4)
{
Writer.WriteLine(inputLine);
}
if (rowCount == 4) break;
}
else
{
if (rowCount >= 2)
{
Writer.WriteLine(inputLine);
}
}
} // end of the while
Writer.Flush();
}
}
} // end of the foreach
} // end of ProcessFile
}
}
You can use LINQ to Take and Skip lines.
public abstract class CsvProcessor
{
private readonly IEnumerable<string> processFiles;
public CsvProcessor(IEnumerable<string> processFiles)
{
this.processFiles = processFiles;
}
protected virtual IEnumerable<string> GetAllLinesFromFile(string fileName)
{
using(var stream = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.Read))
using(var reader = new StreamReader(stream))
{
var line = String.Empty;
while((line = reader.ReadLine()) != null)
{
yield return line;
}
}
}
protected virtual void ProcessFiles()
{
var sb1 = new StringBuilder();
var sb2 = new StringBuilder();
foreach(var file in this.processFiles)
{
var fileName = Path.GetFileNameWithoutExtension(file);
var lines = GetAllLinesFromFile(file);
if(fileName.StartsWith("RO_", StringComparison.InvariantCultureIgnoreCase))
{
sb1.AppendLine(lines.Take(4)); //take only the first four lines
sb2.AppendLine(lines.Skip(4).TakeWhile(s => !String.IsNullOrEmpty(s))); //skip the first four lines, take everything else
}
else if(fileName.StartsWith("Load_", StringComparison.InvariantCultureIgnoreCase)
{
sb2.AppendLine(lines.Skip(1).TakeWhile(s => !String.IsNullOrEmpty(s)));
}
}
// now write your StringBuilder objects to file...
}
protected virtual void WriteFile(StringBuilder sb1, StringBuilder sb2)
{
// ... etc..
}
}

C# System.IO.IOException

I have following code:
using System;
using System.Collections.Generic;
using System.IO;
using VirusTotalNET;
using VirusTotalNET.Objects;
using System.Linq;
using System.Security.Permissions;
namespace VirusTotalNETClient
{
class Program
{
private const string ScanUrl = "http://www.google.com/";
static void Main(string[] args)
{
VirusTotal virusTotal = new VirusTotal("5d8684f50946c2bdeaf5c4fd966f61f3661de808e9d7324b99788d6f4fb7ad57");
//Use HTTPS instead of HTTP
virusTotal.UseTLS = true;
//creating folder for programs reliqies and output log
string folderName = "C:\\OnlineScanner";
System.IO.Directory.CreateDirectory(folderName);
//get list of files to analyse
var paths = Traverse("C:\test");
File.WriteAllLines("C:\\OnlineScanner\\test.txt", paths);
foreach (string line in File.ReadLines("C:\\test.txt"))
{
//Define what file you want to analyse
FileInfo fileInfo = new FileInfo(line);
//Check if the file has been scanned before.
FileReport fileReport = virusTotal.GetFileReport(fileInfo);
bool hasFileBeenScannedBefore = fileReport.ResponseCode == ReportResponseCode.Present;
//If the file has been scanned before, the results are embedded inside the report.
if (hasFileBeenScannedBefore)
{
int detekce = fileReport.Positives;
if (detekce >= 1)
{
using (var writer = new StreamWriter("C:\\OnlineScanner\\OnlineScannerLog.txt"))
{
writer.WriteLine(line);
writer.WriteLine("URL to test: " + fileReport.Permalink);
writer.WriteLine("Detect ratio: " + fileReport.Positives + "/54");
writer.WriteLine("Message: " + fileReport.VerboseMsg);
writer.WriteLine();
writer.WriteLine();
}
}
System.Threading.Thread.Sleep(16000);
}
else
{
ScanResult fileResult = virusTotal.ScanFile(fileInfo);
int detekce = fileReport.Positives;
if (detekce >= 1)
{
using (var writer = new StreamWriter("C:\\OnlineScanner\\OnlineScannerLog.txt"))
{
writer.WriteLine(line);
writer.WriteLine("URL to test: " + fileReport.Permalink);
writer.WriteLine("Detect ratio: " + fileReport.Positives + "/54");
writer.WriteLine("Message: " + fileReport.VerboseMsg);
writer.WriteLine();
writer.WriteLine();
}
}
System.Threading.Thread.Sleep(16000);
}
}
}
private static IEnumerable<string> Traverse(string rootDirectory)
{
IEnumerable<string> files = Enumerable.Empty<string>();
IEnumerable<string> directories = Enumerable.Empty<string>();
try
{
// The test for UnauthorizedAccessException.
var permission = new FileIOPermission(FileIOPermissionAccess.PathDiscovery, rootDirectory);
permission.Demand();
files = Directory.GetFiles(rootDirectory);
directories = Directory.GetDirectories(rootDirectory);
}
catch
{
// Ignore folder (access denied).
rootDirectory = null;
}
foreach (var file in files)
{
yield return file;
}
// Recursive call for SelectMany.
var subdirectoryItems = directories.SelectMany(Traverse);
foreach (var result in subdirectoryItems)
{
yield return result;
}
}
}
}
This code run some time (arround 15secs) but then program crashs.
The error is
System.IO.IOException, process can't access to file C:\hiberfil.sys.
http://upnisito.cz/images/2016_12/319crasherrror.png
Do you have any idea how to solve it?

FileInfo.MoveTo if file exists - rename

I have an application that moves files from one directory to another, but sometimes a conflict occurs and the file already exists in the destination directory.
When that happens, I want to move the file with a different name - e.g. if the file is named test.txt, I want to name it test.txt.1. That's okay, but how do I do it next time, if the file is again test.txt, but in the destination folder we have both test.txt and test.txt.1.
My problem is that I can't find the last created file so that I can read its index and increment it with 1. Any suggestions?
string sourcePath = "C:\\Files\\test.txt";
string filename = Path.GetFileName(sourcePath);
string pathTo = "C:\\Files\\test\\" + filename;
try
{
var fileInfo = new FileInfo(sourcePath);
fileInfo.MoveTo(pathTo);
}
catch (IOException ex)
{
var fileInfo = new FileInfo(sourcePath);
var file = Directory.GetFiles(pathTo, filename+".1").FirstOrDefault();
if (file == null)
{
fileInfo.MoveTo(pathTo+".1");
}
else
{
//find the old file, read it's last index and increment it with 1
}
}
You can use a function like this..
void MoveFileToPath(string sourceFilePath,string destinationDirectory)
{
int index = 1;
string fileName = Path.GetFileName(sourceFilePath);
string destPath = destinationDirectory+fileName;
while(File.Exists(destPath))
{
destPath = string.Format("{0}{1}.{2}",destinationDirectory,fileName,index);
index++;
}
var fileInfo = new FileInfo(sourceFilePath);
Console.WriteLine("Test:"+destPath);
fileInfo.MoveTo(destPath);
}
I have rewritten your code a little because you were programming against the exception, which is something I really do not encourage.
First, it checks if the original file already exists.
Then, as your original code, it tries to create the file with a .1 indexer. If that is already present, it goes through the directory to locate all files that have the same filename.
Last, it goes to find the last index used and increments it by one.
Note that you could also skip the first if-statement in the else-statement because it will still search for the last index used; and if none is present, the lastIndex will stay 0 (with one increment so it will use 1 as index for the new file).
var fileInfo = new FileInfo(sourcePath);
// Check if the file already exists.
if (!fileInfo.Exists)
fileInfo.MoveTo(pathTo);
else
{
var file = Directory.GetFiles(pathTo, filename + ".1").FirstOrDefault();
if (file == null)
{
fileInfo.MoveTo(pathTo + ".1");
}
else
{
// Get all files with the same name.
string[] getSourceFileNames = Directory.GetFiles(Path.GetDirectoryName(pathTo)).Where(s => s.Contains(filename)).ToArray();
// Retrieve the last index.
int lastIndex = 0;
foreach (string s in getSourceFileNames)
{
int currentIndex = 0;
int.TryParse(s.Split('.').LastOrDefault(), out currentIndex);
if (currentIndex > lastIndex)
lastIndex = currentIndex;
}
// Do something with the last index.
lastIndex++;
fileInfo.MoveTo(pathTo + lastIndex);
}
}
Func<int, string> getFileName= delegate(int i)
{
return string.Format("{0}/{1}{2}.{3}", dir, filenameWithouExt, i, ext);
};
int i = 0;
while(File.Exists(getFileName(i)))
{
i++;
}
fileInfo.MoveTo(getFileName(i));
It depends how much files do you have. You can make it more quicker if you have a lot of files:
int i = 0;
while(File.Exists(getFileName(i)))
{
i+=100;
}
i-=90;
while(File.Exists(getFileName(i)))
{
i+=10;
}
i-=9;
while(File.Exists(getFileName(i)))
{
i+=1;
}
I would prefer to write a method that will return a next index for a file and remove try-catch block:
string sourcePath = "C:\\Files\\test.txt";
string filename = Path.GetFileName(sourcePath);
string pathTo = "C:\\Files\\test\\"; // the destination file name would be appended later
var fileInfo = new FileInfo(sourcePath);
if (!fileInfo.Exists)
{
fileInfo.MoveTo(pathTo);
}
else
{
// Get all files by mask "test.txt.*"
var files = Directory.GetFiles(pathTo, string.Format("{0}.*", filename)).ToArray();
var newExtension = GetNewFileExtension(files); // will return .1, .2, ... .N
fileInfo.MoveTo(Path.Combine(pathTo, string.Format("{0}{1}", filename, newExtension)));
}
And the new method for getting the new index:
public static string GetNewFileExtension(string[] fileNames)
{
int maxIndex = 0;
foreach (var fileName in fileNames)
{
// get the file extension and remove the "."
string extension = Path.GetExtension(fileName).Substring(1);
int parsedIndex;
// try to parse the file index and do a one pass max element search
if(int.TryParse(extension, out parsedIndex))
{
if(parsedIndex > maxIndex)
{
maxIndex = parsedIndex;
}
}
}
// increment max index by 1
return string.Format(".{0}", maxIndex + 1);
}

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