C# FileInfo.Length Property for .txt file vs .csv file - c#

I am new to C# and new to Visual Studio. I am about half way through a 16 week class in C# using Visual Studio. I felt like I may have learned enough to understand this piece of code from work and modify it. So far I have been able to understand most of it (after many hours, and using google a lot). However, there are a few places that have me stumped... Or maybe the original programmer didn't use very good logic? I don't know... See the code below:
//This is just a piece of the code... there are hundreds of lines of code above this
private static void OnSizeChange(object source, FileSystemEventArgs e)
{
try
{
// SET PATHS FROM WATCHER
String filePath = e.FullPath;
FileInfo infoForPath = new FileInfo(e.FullPath);
//CHECK FOR TEXT FILE IN ORDER TO VERIFY SIZE TO CONFIRM NEW EMPTY FILE WAS NOT CREATED
String txtExt = ".txt";
Boolean isTxt = e.FullPath.Contains(txtExt);
//Length gets the size, in bytes, of the current file.
if (!isTxt && infoForPath.Length > 5 || isTxt && infoForPath.Length > 0)
What you can not see here is that the file will either be a .txt file or a .csv file. My question is about the if statement.
What is the if statement checking?
From what I can gather, it is checking to see if there is a ".txt" in the file path && the length of the file in bytes is "> 5" (for a non .txt file) or "> 0" (for a .txt file).
What is the reason for the "5" and the "0"?
Is there some inherent reason for these numbers as pertains to .txt and .csv files?
If it helps, i found this code online, which is similar and could be used for testing I think from a C# command prompt application.
using System;
using System.IO;
class Program
{
static void Main()
{
const string fileName = #"C:\programs\file.txt";
// Part 1: create new FileInfo get Length.
FileInfo info = new FileInfo(fileName);
long length = info.Length;
// Part 2: print length in bytes.
Console.WriteLine("LENGTH IN BYTES: {0}", length);
}
}
Output
LENGTH IN BYTES: 60

To start Boolean isTxt = e.FullPath.Contains(txtExt); is error prone and not the best way to do this.
You should instead get the extension by doing var fileExtenstion = infoForPath.Extension
this will get you the extension of the file. For more info about this look here. Now that you have the extension you can check if the extension is .txt and return a bool or change how you're if statement works.
The reason for checking for the length of 0 for text files is because text files contain no data (length) when they are empty. I don't know for sure but CSV files may have a default length of 5. You can use the console app code you posted if you want to check this

Related

Program that implements .CSV file data - Need assistance on implementing a Console.Readline() Method

I'm a novice programmer and I've recently written a C# program that implements .CSV file data which compiles correctly.
It functions perfectly and have met all but one of the requirements to complete this assignment.
The requirement is this:
"The program must allow me to pass a data-file name on the command line. If I pass the filename on the command line you must open that file for reading.(ie the .CSV file). "
I just don't understand how to implement a function that will be able to read the .CSV file on another desktop other than my own. I've been told that I would need to use the Console.Readline() Method but don't know where to start.
This is how I have it set in my current program:
class Program
{
static void Main(string[] args)
{
char choes;
bool file_test = true;
string file = "";
var key = ".";
{
file = #"C:\Users\BorusseGooner\desktop\projectData.csv";
Console.Clear();
Console.WriteLine();
StreamReader reader = new StreamReader(File.OpenRead(file));
This hard-coded path that will only work on my computer.
The receivables are:
1. The program.cs file
2. The .CSV
Any help would be greatly appreciated to revise my code to be able to be used & accessed on other computers.
"The program must allow me to pass a data-file name on the command line. If I pass the filename on the command line you must open that file for reading.(ie the .CSV file). "
This is knows as a command line argument, and has nothing to do with the Console.ReadLine() method.
Command line arguments are passed to your .Net executable using the args argument of the Main method.
If gives you the ability execute your program like this -
c:\>YourProgramName.exe CsvFilePathToOpen - where YourProgramName.exe is the name of your executable file and CsvFilePathToOpen is the path to the csv vile you want to open. Please note that since you're passing a path, you'll most likely need to wrap it with quotation marks, since it will most likely contain characters that can mess it up (like spaces, for instance) - so it should look like this:
c:\>YourProgramName.exe "d:\Some folder\ some file.csv"
In your code, you should check the length of the args argument, and if it has a length of at least 1, you should try to use it's content as the path, instead of the hard coded one:
static void Main(string[] args)
{
char choes;
bool file_test = true;
string file = args.Length > 0: args[0] : #"C:\Users\BorusseGooner\desktop\projectData.csv";
var key = ".";
//... rest of the code here...

Issue in file access with absolute paths

I've created a .NetCore console application in which am trying to check if a file exists using its absolute path, but am facing issues, I always get a false response even though the file exists. Even though I pass absolute path as parameter to API, it always prefixes the current working directory, so the path gets evaluated as doesn't exists.
I'm running this code on a windows 10 desktop and the application is created using .NetCore 2.1. I've tried various different methods to evaluate the existence of file like FileInfo Class instance and File.Exists static method. They've failed so far. I've diagnosed the issue, but I couldn't find a way to fix it.
using System;
using System.IO;
namespace FileAccess
{
class Program
{
static void Main(string[] args)
{
FileInfo fileInfo = new FileInfo(#"‪D:\ScriptData\test.zip");
Console.WriteLine($"Full Name: {fileInfo.FullName}");
Console.WriteLine($"FileInfo.Exists: {fileInfo.Exists}");
Console.Write($"File.Exists with #: {File.Exists(#"‪D:\ScriptData\test.zip")}")
Console.ReadLine();
}
}
}
The output of the code is:
Full Name: D:\Work\Samples\FileAccess\FileAccess\bin\Debug\netcoreapp2.1\?D:\ScriptData\test.zip
False
False
Even though am passing the absolute path, it prefixes the current working directory to the path I've passed. I've checked the Access to the file, its all fine, still I get false as response for both the cases.
Screenshot of Error
Screenshot of Debug Info
Judging your screen shot and the output, there is an invisible character at the start of the file path. That will cause .NET not to recognize it is an absolute path and automatically it will make it an absolute path itself.
If you use this code, you will notice that the inserted ? causes the problem here:
System.IO.FileInfo fi = new System.IO.FileInfo(#"?D:\some_file.ext");
Which outputs: C:\Users\...\ConsoleApp8\bin\Debug\netcoreapp2.2\?D:\some_file.ext.
Instead of:
System.IO.FileInfo fi = new System.IO.FileInfo(#"D:\some_file.ext");
Which outputs: D:\some_file.ext.
If you put your code in a HEX editor, you will see there is indeed a character before D:.
Thank goodness you cut and paste your original code! I know you did because when I cut and paste your code I can see that you have invisible characters after the open quote and before the D:\.
These two lines look identical but they're not! Cut and paste them if you don't believe me!
Your code:
FileInfo fileInfo = new FileInfo(#"‪D:\ScriptData\test.zip");
Fixed code:
FileInfo fileInfo = new FileInfo(#"D:\ScriptData\test.zip");
Here's what the binary editor shows.
You've got E2 80 AA secretly stuck in your source code file at the beginning of your filename. Which happens to be the UTF-8 representation of the LEFT-TO-RIGHT EMBEDDING character.

How to Copy and move files and folders in C# [duplicate]

This question already has answers here:
Copy Folders in C# using System.IO
(9 answers)
Closed 4 years ago.
How can we copy and move folders in one folder to another folder.
void BtncopyClick(object sender, EventArgs e)
{
string filename=#"E:\\Files\\Reports\\R^ECG^_0_1688^Jones^^_20160711065157_20160711065303 - Copy (4) - Copy.pdf";
string sourcepath=#"E:\\Anusha";
string targetpath=#"E:\\Anusha\\aaa";
string sourcefile= System.IO.Path.Combine(sourcepath,filename);
string destfile= System.IO.Path.Combine(targetpath,filename);
if (!System.IO.Directory.Exists(targetpath))
{
System.IO.Directory.CreateDirectory(targetpath);
}
System.IO.File.Copy(sourcefile, destfile, true);
if (System.IO.Directory.Exists(sourcepath))
{
string[] files = System.IO.Directory.GetFiles(sourcepath);
// Copy the files and overwrite destination files if they already exist.
foreach (string s in files)
{
// Use static Path methods to extract only the file name from the path.
filename = System.IO.Path.GetFileName(s);
destfile = System.IO.Path.Combine(targetpath, filename);
System.IO.File.Copy(s, destfile, true);
}
}
else
{
MessageBox.Show("File doesn't exist");
}
}
void BtnmoveClick(object sender, EventArgs e)
{
String path = "E:\\Files\\25-11-2017";
String path2 = "E:\\Anusha\\aaa\\25-11-2017";
if (!File.Exists(path))
{
{
// This statement ensures that the file is created,
// but the handle is not kept.
using (FileStream fs = File.Create(path)) {}
}
System.IO.Directory.Move("E:\\Files\\25-11-2017",#"E://Anusha//aaa");
// Move the file.
File.Move(path, path2);
MessageBox.Show("File Moved");
}
}
I have the above code to copy and move the folder,I am not getting any compiling errors. However, when i am trying to click on button on the output form it was showing as termination.
Update
Code works with out any error but it was getting termination Error as cannot create a file as it is already exists
Hope this helps
How to: Copy, Delete, and Move Files and Folders (C# Programming Guide)
You can use System.IO.File, System.IO.Directory, System.IO.FileInfo, and System.IO.DirectoryInfo classes from the System.IO namespace.
I am not sure what you are trying to do, but I am seeing a lot of problems here.
1) In the line
System.IO.Directory.Move("E:\\Files\\25-11-2017",#"E://Anusha//aaa");
you are using // as directory separator in the second argument. You should change it to
System.IO.Directory.Move("E:\\Files\\25-11-2017","E:\\Anusha\\aaa");
2) Sometimes you are using verbatim strings incorrectly. For example, in the line
string sourcepath=#"E:\\Anusha";
you are using a verbatim string which means that the compiler ignores the escape sequences in that string. Hence, your application later won't find that path. Instead, use one of the following:
string sourcepath=#"E:\Anusha";
string sourcepath="E:\\Anusha";
3) The structure of your BtnmoveClick is quite weird. The line
System.IO.Directory.Move("E:\\Files\\25-11-2017","E:\\Anusha\\aaa");
moves the contents of E:\files\25-11-2017 to E:\Anusha\aaa, but only if the latter does NOT exist yet. If it already exists, that line will cause an exception (which probably makes your application terminate).
Furthermore, after you already have moved the directory contents in the line shown above, you are again trying to move something in the line
File.Move(path, path2);
But path and path2 are strings which describe directories, not files, so I wouldn't do it that way. Furthermore, since you already have moved the directory (more precise: its contents) in the previous line, I am asking myself what exactly the purpose of that line is.
I didn't look into your BtncopyClick yet, so let's concentrate on BtnmoveClick for now. Please try to fix the issues described so far, and if you have further issues, report back.
As a general recommendation: If you really want to learn C#, then don't copy-and-paste randomly selected examples; you'll never learn anything useful that way. Instead, read the documentation of the .net framework on MSDN or read a good book - this will gain you a deep understanding.

Read a file from an unknown location?

I have got this read file code from microsoft
#"C:\Users\computing\Documents\mikec\assignment2\task_2.txt"
That works fine when im working on it, but when i am to hand in this assignment my lecturer isn't going to have the same directory as me.
So i was wondering if there is a way to read it from just the file the program is held in?.
I was thinking i could add it as a resource but im not sure if that is the correct way for the assignment it is meant to allow in any file.
Thanks
You can skip the path - this will read file from the working directory of the program.
Just #"task_2.txt" will do.
UPDATE: Please note that method won't work in some circumstances. If your lecturer uses some automated runner (script, application whatsoever) to verify your app then #ken2k's solution will be much more robust.
If you want to read a file from the directory the program is in, then use
using System.IO;
...
string myFileName = "file.txt";
string myFilePath = Path.Combine(Application.StartupPath, myFileName);
EDIT:
More generic solution for non-winforms applications:
string myFilePath = Path.Combine(Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location), myFileName);
If it is a command line application, you should take the file name as a command line argument instead of using a fixed path. Something along the lines of;
public static void Main(string[] args)
{
if (args == null || args.Length != 1)
{
Console.WriteLine("Parameters are not ok, usage: ...");
return;
}
string filename = args[0];
...
...should let you get the filename from the command.
You could use the GetFolderPath method to get the documents folder of the current user:
Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments)
and to exemplify:
string myDocuments = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
string file = Path.Combine(myDocuments, #"mikec\assignment2\task_2.txt");
// TODO: do something with the file like reading it for example
string contents = File.ReadAllText(file);
Use the relative path.
you can put your file inside the folder where your application resides.
you can use Directory.GetCurrentDirectory().ToString() method to get the current folder of the application in. if you put your files inside a sub folder you can use
Directory.GetCurrentDirectory().ToString() + "\subfolderName\"
File.OpenRead(Directory.GetCurrentDirectory().ToString() + "\fileName.extension")
StreamReader file = new StreamReader(File.OpenRead(Directory.GetCurrentDirectory().ToString() + ""));
string fileTexts = file.ReadToEnd();

C# Creating a text file contains the error logs

I have created a text file to save the error in that created file. I have a button which, once pressed, generates an error which should be saved to the file. But if I press the button twice, it will overwrite the first error generated, because the contents of the file are overwritten. I want to generate a another separate file to save the new error. A new file should be generated for each new error.
Thanks in advance
Simple use: FileExists Method and then if it exists pick a new name. Alternatively you could just append to the file.
PSUDO:
public string checkFileName(string fileName){
if(File.Exists(fileName)){
/Pick a new one
newFileName= fileName + DateTime.Now.ToLongDateString()
return checkFileName(newFileName)
}
return fileName
}
This could be the perfect link for you How to Open and Append a log file
You can add time stamp in filename, in this case you would get new file each time.
private void SaveErrorMessage(string errorMessage)
{
string errorFile = null;
for( int x = 0; x < Int32.MaxValue; ++x )
{
errorFile = string.Format(CultureInfo.InvariantCulture, "error-{0}.txt", x);
if( !System.IO.File.Exists(errorFileTest) )
{
break;
}
}
File.WriteAllText(errorFile, errorMessage);
}
This will overwrite the last file after you've had Int32.MaxValue files, but that'll take a while.
An alternative (and probably better) approach would be to simply append to the file, rather than creating a new one.
You may also want to consider using a more robust logging solution, such as log4net.
Creating file in C# is probably what you're looking for.
So you want to generate a unique file name for each error that occurs in your program? Probably the easiest way to accomplish this is to use the date/time when the error occured to name the file. In the function where you are writing to the file you will want to name the file like this:
string filename = LogPath + DateTime.Now.ToString("yyyyMMdd.HHmmss") + ".err";
Where LogPath is the path to the folder you want to write the error files to.

Categories

Resources