c# value not being stored into accessor - c#

I have 4 class files Driver class (contains main method)
UserInput class (contains GenerateLines & TxtLoadFile methods)
FileHandling.class(contains LoadFile & LoadingFile methods)
Crypting class (empty class at the moment)
My issue is I am trying to get the user to choose which directory out of three to choose a file from. Once chosen I want them to input the file name (.txt) and when that is done I want that value stored and taken to FileHandling class and the LoadFile accessor stores the value into 'TxtFile' variable. I then want to use 'TxtFile' in the method LoadingFile to load the file.
Issue is the value gets stored while in UserInput class but when I call: LoadingFile method in the Driver class it drops the value.
Bear in mind I am student still learning C#, so may not be the best constructed programs as I am just practicing for assignment.
EDIT: I forgot to mention I did check this through debugger but I could not work out how to fix it
Driver class :
namespace UniAssignVigereneCipher
{
class Driver
{
static void Main(string[] args)
{
UserInput UI = new UserInput();
Crypting CR = new Crypting();
FileHandling FH = new FileHandling();
Console.WriteLine(UI.test);
Console.WriteLine(UI.test2);
FH.LoadingFile();
}
}
}
UserInput class:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
namespace UniAssignVigereneCipher
{
class UserInput
{
public string test = GenerateLines();
public string test2 = TxtLoadFile();
public static string GenerateLines()
{
string input;
Console.WriteLine("Would you like to encrypt/decrypt a .txt(t) file or a piece text string(s)?\r\nPlease type (t) or (s)");
input = Console.ReadLine();
switch (input)
{
case "t":
case "T":
Console.WriteLine("You have selected a txt file.");
break;
case "s":
case "S":
Console.WriteLine("You have selected to input your own text string.");
break;
default:
break;
}
return input;
}
public static string TxtLoadFile()
{
FileHandling Location = new FileHandling();
int n;
string FileInput;
string TxtFileLoc;
Console.WriteLine("Please choose the location of the .txt file you would like to load from.\r\n1 (Current Location): {0} \r\n2 (Desktop): {1} \r\n3 (My Documents): {2}", Location.CurrentDir, Location.DesktopPath,Location.DocumentsPath);
FileInput = Console.ReadLine();
bool test = int.TryParse(FileInput, out n);
switch (n)
{
case 1:
Console.WriteLine("File Location: {0} \r\nName of file to load: ", Location.CurrentDir);
TxtFileLoc = Console.ReadLine();
Location.LoadFile = Location.DesktopPath + "\\" + TxtFileLoc;
break;
case 2:
Console.WriteLine("File Location: {0} \r\nName of file to load: ", Location.DesktopPath);
TxtFileLoc = Console.ReadLine();
Location.LoadFile = Location.DesktopPath + "\\" + TxtFileLoc;
break;
case 3:
Console.WriteLine("File Location: {0} \r\nPName of file to load: ", Location.DocumentsPath);
TxtFileLoc = Console.ReadLine();
Location.LoadFile = Location.DocumentsPath + "\\" + TxtFileLoc;
break;
default:
break;
}
return FileInput;
}
}
}
FileHandling class
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
namespace UniAssignVigereneCipher
{
class FileHandling
{
public string DesktopPath = Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory);
public string DocumentsPath = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
public string CurrentDir = Environment.CurrentDirectory;
string TxtFile;
public string LoadFile
{
get
{
return TxtFile;
}
set
{
TxtFile = value;
}
}
public void LoadingFile()
{
Console.WriteLine("name:" + TxtFile);
StreamReader LF = new StreamReader(TxtFile);
string FileContent = LF.ReadLine();
Console.WriteLine(FileContent);
}
}
}

Try:
static void Main(string[] args)
{
UserInput UI = new UserInput();
Crypting CR = new Crypting();
FileHandling FH = new FileHandling();
Console.WriteLine(UI.test);
Console.WriteLine(UI.test2);
FH.LoadFile = UI.test2;
FH.LoadingFile();
}
Note: It's very odd to put your worker methods into the class construction. it would probably be better to call them like this:
UserInput UI = new UserInput();
string textFile = UI.TxtLoadFile();
//... later on...
FH.LoadFile = textFile;

Related

File format could not be determined using Metadata Extractor 2.4.3

I'm trying to make a program that automatically copies and sorts the pictures from an SD card to an external hard drive using Metadata Extractor 2.4.3
I don't seem to find any prolem but every time I run the code, an unhandled exception prompts up.
Here's the error:
Unhandled Exception: MetadataExtractor.ImageProcessingException: File format could not be determined
at MetadataExtractor.ImageMetadataReader.ReadMetadata(Stream stream)
at MetadataExtractor.ImageMetadataReader.ReadMetadata(String filePath)
at file_sorter.File..ctor(String filepath) in
C:\Users\ropra\Documents\file_sorter\file_sorter\File.cs:line 27
at file_sorter.Program.Main(String[] args) in
C:\Users\ropra\Documents\file_sorter\file_sorter\Program.cs:line 27
Here's the code:
Program.cs:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using MetadataExtractor;
namespace file_sorter
{
class Program
{
static void Main(string[] args)
{
// Define paths
string sandisk = #"Z:/Images/RAW";
string sd = #"Y:/DCIM/100_FUJI";
// Count elements in sd
string[] photoPaths = System.IO.Directory.GetFiles(sd);
Console.WriteLine("Counting elements in SD card...");
// Create object array
File[] photos = new File[photoPaths.Count()];
for (int i = 0; i < photos.Count(); i++)
{
photos[i] = new File(photoPaths[i]);
}
// Create tree and copy files
foreach (var item in photos)
{
string fileName = item.filename;
string sourcePath = item.sourcepath;
string targetPath = sandisk + "/" + item.year + "/" + item.month + "/" + item.day;
string sourceFile = System.IO.Path.Combine(sourcePath, fileName);
string destFile = System.IO.Path.Combine(targetPath, fileName);
Console.WriteLine("Now copying: {0} into {1}", fileName, targetPath);
System.IO.Directory.CreateDirectory(targetPath);
System.IO.File.Copy(sourceFile, destFile, true);
}
}
}
}
File.cs:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using MetadataExtractor;
namespace file_sorter
{
public class File
{
public string filename;
public string path;
public string year;
public string month;
public string day;
public string sourcepath;
public File(string filepath)
{
path = filepath;
filename = path.Substring(path.LastIndexOf("\\") + 1);
sourcepath = path.Substring(0, path.LastIndexOf("\\"));
string rawDate = "";
var metadata = ImageMetadataReader.ReadMetadata(path);
for (int i = 0; i < metadata.Count(); i++)
{
for (int j = 0; j < metadata[i].TagCount; j++)
{
if (metadata[i].Name == "Exif IFD0" && metadata[i].Tags[j].Name == "Date/Time")
{
rawDate = metadata[i].Tags[j].Description;
}
}
}
int separator = rawDate.IndexOf(":");
year = rawDate.Substring(0, separator);
string sub = rawDate.Substring(separator + 1);
separator = sub.IndexOf(":");
month = sub.Substring(0, separator);
sub = sub.Substring(separator + 1);
separator = sub.IndexOf(" ");
day = sub.Substring(0, separator);
}
public void ShowFormatedDate()
{
Console.WriteLine("Path: {0}", path);
Console.WriteLine("File: {0}", filename);
Console.WriteLine("Dir: {0}", sourcepath);
Console.WriteLine("Year: {0}", year);
Console.WriteLine("Month: {0}", month);
Console.WriteLine("Day: {0}", day);
Console.WriteLine("");
}
}
}
Thank you in advance.
OK, so having given up and sorting all files manually, I came across an .xml file containing the metadata of a single .RAF file, I'm guessing my camera put it there.
This program does not handle MetadataExtractor non-supported files, hence the problem.
ImageProcessingException: File format could not be determined
This exception means that the library didn't identify the file it was given as anything it knows how to read. For example, if you give a text file to the library, you will see this exception.
Perhaps you could catch this exception type and use a different code path for such files.

How can I achieve to not only read one line from the txt file but also all the lines?

Im a beginner programmer. I started to learn c# about two weeks ago, and now I'm programming a simple Login/Register program but it's a bit hard for me. My question is: there is this
adat1= olvas.ReadLine(); code, and I think this is for read only one line from the txt. How can I achieve to read all the lines and then select the UserName which we write into the Console? After the solution we will be able to create new Users.
Thank you guys for your help!
My source code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
using System.Threading;
namespace Gyak
{
class Program
{
static void Main(string[] args)
{
bool helyes = false;
do {
Console.Clear();
Console.WriteLine("1 = Login\n2 = Registration");
int valasz = int.Parse(Console.ReadLine());
if (valasz == 1)
{
StreamReader olvas = new StreamReader(#"D:\k\Gyakorlás 2\UserName.txt", Encoding.Default);
while (!olvas.EndOfStream)
{
string adat1;
helyes = true;
Console.Clear();
Console.WriteLine("Login");
Console.WriteLine("UserName: ");
Console.Write("Password: ");
Console.SetCursorPosition(10, 1);
string valasz1 = Console.ReadLine();
adat1 = olvas.ReadLine();
Console.SetCursorPosition(10, 2);
string valasz2 = Console.ReadLine();
if (adat1.StartsWith(valasz1))
{
string[] keresett_adat = adat1.Split(':');
string keresett_eredmény = keresett_adat[1];
if (valasz2 == keresett_eredmény)
{
Console.WriteLine("Login Succeeded");
Console.ReadLine();
}
else
{
Console.WriteLine("Access Denied!\nTry again!");
Console.ReadLine();
}
}
}
}
else if (valasz == 2)
{
StreamWriter iras = new StreamWriter(#"D:\k\Gyakorlás 2\UserName.txt", true, Encoding.Default);
helyes = true;
Console.Clear();
Console.WriteLine("Registration");
Console.WriteLine("UserName: ");
Console.Write("Password: ");
Console.SetCursorPosition(10, 1);
string valasz3 = Console.ReadLine();
Console.SetCursorPosition(10, 2);
string valasz4 = Console.ReadLine();
iras.WriteLine( "\n" + valasz3 + ":" + valasz4);
iras.Close();
}
else
{
helyes = false;
Console.WriteLine("Incorrect!");
Thread.Sleep(2000);
}
}while(helyes != true);
}
}
}
You can use File.ReadAllText or File.ReadAllLines.

Parsing a vCard file

I want to retrieve the data from a .vcf file. It is in vcf format.
I need the regular expression formula for each item of data mentioned below. I tried but could not make it work.
BEGIN:VCARD
VERSION:2.1
FN;CHARSET=utf-8:s James F ' Ernande.
ADR;WORK;X-EDIT=0;X-POS=280,43,54,269,0,0,0,0;CHARSET=utf-8:;;P.O. Box No: 570, P. C-112, Ruwi Muscat, Sultanate Ofoman;;;;
X-IS-TAKE-ADR;CHARSET=utf-8:23.62866567746918;58.26649072858852;
N;X-EDIT=0;X-POS=33,89,29,178;CHARSET=utf-8:s;James F ' Ernande. ;;;
EMAIL;WORK;X-EDIT=0;X-POS=116,59,26,237;CHARSET=utf-8:james#om.bluerhine.com
EMAIL;WORK;X-EDIT=0;X-POS=142,61,26,234;CHARSET=utf-8:oman#onn.bluerhine.com
EXCHANGEDATE:2019-06-16
EXCHANGEDATE:2019-06-16
AUTHOR:IntSig-iOS-iPhone
ORG;WORK;X-EDIT=0;X-POS=0,0,0,0,59,29,33,295,0,0,0,0;CHARSET=utf-8:;Business Development Manaus)r;
TEL;WORK;X-EDIT=0;X-POS=88,107,23,142;CHARSET=utf-8:+96897641700
TEL;WORK;X-EDIT=0;X-POS=332,133,28,182;CHARSET=utf-8:+96822022247
TEL;WORK;X-EDIT=0;X-POS=328,36,27,92;CHARSET=utf-8:24796647
END:VCARD
Code:
Regex regex = new Regex(#"(?<strElement>(FN)) (:(?<strFN>[^\r\n]*))", options);// For retrieving the First Name
Regex regex = new Regex(#"((?<strElement>(EMAIL)) (;*(?<strAttr>(HOME|WORK)))* (;(?<strPref>(PREF)))* (;[^:]*)* (:(?<strValue>[^\n\r]*)))");//for retrieving Email
I am not getting the exact regular expression formula required.
Here is a simple parser :
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.IO;
namespace ConsoleApplication124
{
class Program
{
static void Main(string[] args)
{
string input =
"BEGIN:VCARD\n" +
"VERSION:2.1\n" +
"FN;CHARSET=utf-8:s James F ' Ernande.\n" +
"ADR;WORK;X-EDIT=0;X-POS=280,43,54,269,0,0,0,0;CHARSET=utf-8:;;P.O. Box No: 570, P. C-112, Ruwi Muscat, Sultanate Ofoman;;;;\n" +
"X-IS-TAKE-ADR;CHARSET=utf-8:23.62866567746918;58.26649072858852;\n" +
"N;X-EDIT=0;X-POS=33,89,29,178;CHARSET=utf-8:s;James F ' Ernande. ;;;\n" +
"EMAIL;WORK;X-EDIT=0;X-POS=116,59,26,237;CHARSET=utf-8:james#om.bluerhine.com\n" +
"EMAIL;WORK;X-EDIT=0;X-POS=142,61,26,234;CHARSET=utf-8:oman#onn.bluerhine.com\n" +
"EXCHANGEDATE:2019-06-16\n" +
"EXCHANGEDATE:2019-06-16\n" +
"AUTHOR:IntSig-iOS-iPhone\n" +
"ORG;WORK;X-EDIT=0;X-POS=0,0,0,0,59,29,33,295,0,0,0,0;CHARSET=utf-8:;Business Development Manaus)r;\n" +
"TEL;WORK;X-EDIT=0;X-POS=88,107,23,142;CHARSET=utf-8:+96897641700\n" +
"TEL;WORK;X-EDIT=0;X-POS=332,133,28,182;CHARSET=utf-8:+96822022247\n" +
"TEL;WORK;X-EDIT=0;X-POS=328,36,27,92;CHARSET=utf-8:24796647\n" +
"END:VCARD";
ParseVCF parseVCF = new ParseVCF(input);
}
}
public class ParseVCF
{
public string version { get; set; }
public List<string> data = new List<string>();
enum State
{
FIND_BEGIN,
GET_VERSION,
PROCESS_DATA,
FOUND_END
}
public ParseVCF(string input)
{
StringReader reader = new StringReader(input);
string line = "";
State state = State.FIND_BEGIN;
while(((line = reader.ReadLine()) != null) && (state != State.FOUND_END))
{
line = line.Trim();
if (line.Length > 0)
{
switch (state)
{
case State.FIND_BEGIN :
if (line.StartsWith("BEGIN:"))
{
state = State.GET_VERSION;
}
break;
case State.GET_VERSION :
string[] split = line.Split(new char[] { ':' });
version = split[1];
state = State.PROCESS_DATA;
break;
case State.PROCESS_DATA :
if(line.StartsWith("END"))
{
state = State.FOUND_END;
}
else
{
data.Add(line);
}
break;
}
}
}
}
}
}

How can I compare variables and set a variable to new text found in one of the variables in c#

I need to compare files found in a directory with another directory and print the files new files found in a directory into the console. I have it setup so it takes the files and assigns it to a variable. The other directory is assigned to another variable. How can I print the new data in one of the variables to command prompt?
The language I am using is c#.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
namespace ConsoleApp1
{
class Program
{
static void Main(string[] args)
{
Console.Write("Write the path of the old file folder: ");
string path = Console.ReadLine();
listFilesFromDirectory(path);
Console.Write("Write the path of the new file folder: ");
string pathTwo = Console.ReadLine();
listFilesFromDirectoryMore(pathTwo);
Console.WriteLine("Press Enter to continue:");
Console.Read();
}
static void listFilesFromDirectory(string workingDirectory)
{
// get a list of files in a directory,
// based upon a path that is passed into the function
string[] filePaths = Directory.GetFiles(workingDirectory);
foreach (string filePath in filePaths)
{
// use the foreach loop to go through the entire
// array one element at a time write out
// the full path and file name of each of the
// elements in the array
Console.WriteLine(filePath);
string oldfile = (filePath);
}
}
static void listFilesFromDirectoryMore(string workingDirectoryTwo)
{
// get a list of files in a directory,
// based upon a path that is passed into the function
string[] filePathsTwo = Directory.GetFiles(workingDirectoryTwo);
foreach (string filePathTwo in filePathsTwo)
{
// use the foreach loop to go through the entire
// array one element at a time write out
// the full path and file name of each of the
// elements in the array
Console.WriteLine(filePathTwo);
string newfile = (filePathTwo);
}
}
}
}
using System;
using System.Collections.Generic;
using System.IO;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
Console.Write("Write the path of the old file folder: ");
string pathA = Console.ReadLine();
Console.Write("Write the path of the new file folder: ");
string pathB = Console.ReadLine();
Console.WriteLine("Press Enter to continue:");
List<string> folderA = new List<string>();
foreach (string filePath in Directory.GetFiles(pathA))
{
folderA.Add(Path.GetFileName(filePath));
}
List<string> folderB = new List<string>();
foreach (string filePath in Directory.GetFiles(pathB))
{
folderB.Add(Path.GetFileName(filePath));
}
Console.Write("New files in folder" + pathA + " : ");
Print(folderA, folderB);
Console.WriteLine("------------------------------------");
Console.Write("New files in folder" + pathB + " : ");
Print(folderB, folderA);
Console.Read();
}
static void Print(List<string> lstA, List<string> lstB)
{
foreach (string fileName in lstA)
{
if (!lstB.Contains(fileName))
{
Console.Out.WriteLine(fileName);
}
}
}
}
}

An Issue With Writing In A File In C#

I developed a simple program that asks the user if he wants to add a new record to a file or display all the records contained in the file, but I seem to have a problem in writing to the file. The file is created but still nothing is written in it. The reading function works fine since I wrote something in the file to see if it works.
Here is the code...
using System;
using System.IO;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace F01
{
class Program
{
static int ID;
static String Name;
static void Main(string[] args)
{
FileStream MyFiler = new FileStream("MyFile.txt", FileMode.OpenOrCreate, FileAccess.ReadWrite);
StreamReader FileReader = new StreamReader(MyFiler);
StreamWriter FileWriter = new StreamWriter(MyFiler);
Console.WriteLine("Please Select One Of The Following Options... ");
Console.WriteLine("1. Enter A New Record In The File.");
Console.WriteLine("2. Read All The Records From The File.");
int Choice = int.Parse(Console.ReadLine());
if (Choice == 1)
{
Console.WriteLine("Enter The ID: ");
ID = int.Parse(Console.ReadLine());
FileWriter.WriteLine(ID);
Console.WriteLine("Enter The Name: ");
Name = Console.ReadLine();
FileWriter.WriteLine(Name);
}
else if (Choice == 2)
{
FileWriter.Close();
String fileText = File.ReadAllText("MyFile.txt");
for (int i = 0; i < fileText.Length; i++)
{
Console.Write(fileText[i]);
}
}
FileReader.Close();
}
}
}
Thanks in advance :)
You're not closing the writer in the only situation in which you're using it - "choice 1". Basically the data is being buffered, and lost when the process exits because you haven't closed the writer.
I would strongly advise you to:
Only open the file when you need to
Use local variables instead of class variables unless you need them in other methods
Use the File static methods to make all of this easier
Use using statements to clean up resources at the end of them (if you need a writer or a stream at all, that is...)
Break your code up into methods for separate operations
Name your variables in camelCase rather than PascalCase
Print your file a line at a time rather than a letter at a time
So for example:
using System;
using System.IO;
class Program
{
const string FileName = "MyFile.txt";
static void Main(string[] args)
{
Console.WriteLine("Please Select One Of The Following Options... ");
Console.WriteLine("1. Enter A New Record In The File.");
Console.WriteLine("2. Read All The Records From The File.");
int choice = int.Parse(Console.ReadLine());
switch (choice)
{
case 1:
AddEntry();
break;
case 2:
ReadFile();
break;
default:
Console.WriteLine("Sorry, that's not a valid option");
break;
}
}
static void AddEntry()
{
Console.WriteLine("Enter the ID:");
int id = int.Parse(Console.ReadLine());
Console.WriteLine("Enter the name:");
string name = Console.ReadLine();
File.AppendAllLines(FileName, new[] { id.ToString(), name });
}
static void ReadFile()
{
foreach (var line in File.ReadLines(FileName))
{
Console.WriteLine(line);
}
}
}
I see your MyFiler which is a FileStream type which is IDisposable type is not wrapped in using statement, nor do you call .Dispose() manually. Same for your readers (which are also disposable types). This can lead to this type of behavior...
Try the follwing:
using System;
using System.IO;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace F01
{
class Program
{
static int ID;
static String Name;
static void Main(string[] args)
{
using(FileStream MyFiler = new FileStream("MyFile.txt", FileMode.OpenOrCreate, FileAccess.ReadWrite))
{
using(StreamReader FileReader = new StreamReader(MyFiler))
{
using(StreamWriter FileWriter = new StreamWriter(MyFiler))
{
Console.WriteLine("Please Select One Of The Following Options... ");
Console.WriteLine("1. Enter A New Record In The File.");
Console.WriteLine("2. Read All The Records From The File.");
int Choice = int.Parse(Console.ReadLine());
if (Choice == 1)
{
Console.WriteLine("Enter The ID: ");
ID = int.Parse(Console.ReadLine());
FileWriter.WriteLine(ID);
Console.WriteLine("Enter The Name: ");
Name = Console.ReadLine();
FileWriter.WriteLine(Name);
}
else if (Choice == 2)
{
FileWriter.Close();
String fileText = File.ReadAllText("MyFile.txt");
for (int i = 0; i < fileText.Length; i++)
{
Console.Write(fileText[i]);
}
}
FileReader.Close();
}
}
}
}
}
}

Categories