I have a problem with reading a bunch of files using the following C# code in my VS2008 project
public void FindFiles()
{
//Root
targetPath = Directory.GetDirectoryRoot(Directory.GetCurrentDirectory()) + "WriteToCSVFolder";
}
public void ReadFiles()
{
fileNameList_Original = Directory.GetFiles(targetPath);
string defaultFileName = "file_";
int counter = 0;
foreach (string fileName in Directory.GetFiles(targetPath))
{
fullFileText_Original[counter] = File.ReadAllText(targetPath);
//fileNameList_Original[counter]
counter++;
}
counter = 0;
}
Now please consider im just fast ticking this so I haven't bothered doing optimizations or anything yet. Just noticed that when I do a read action with the files NOT open and UAC (user account control) disabled on W7 64bit , and also not sharing it over network dropbox or anything else. It's just some ABC BLA FOO files I just made and wanted to test, they are in the correct directory marked targetpath in my system folder and the program is being run from the correct drive.
Is it just something stupid in the code or?
And oh yeah , the application was marked as full trust.
Any ideas?
EDIT:
With the new idea implemented from the comment section below:
Changed the code from
public void ReadFiles()
{
fileNameList_Original = Directory.GetFiles(targetPath);
string defaultFileName = "file_";
int counter = 0;
foreach (string fileName in Directory.GetFiles(targetPath))
{
fullFileText_Original[counter] = File.ReadAllText(targetPath);
//fileNameList_Original[counter]
counter++;
}
counter = 0;
}
TO
public void ReadFiles()
{
//Store all files names in a string array in one go
fileNameList_Original = Directory.GetFiles(targetPath);
string defaultFileName = "file_";
int counter = 0;
foreach (string fileName in Directory.GetFiles(targetPath))
{
//removed the storing file names, was redundant
//added the suggested idea to the proper array
fullFileText_Original[counter] = File.ReadAllText(fileName);
//fileNameList_Original[counter]
counter++;
}
counter = 0;
}
Gives me nullreference exception on File, not sure what my conclusion should be from this error. Admitting that I am pretty tired atm , probably going to realize exactly what it was on the way home :)
FINAL EDIT:
See answers my own post.
This code works fine. I had to be fired for not fixing this almost...... trying to assign values to uninitialized arrays and ignoring any mutable size....... Never happened!
foreach (string fileName in Directory.GetFiles(targetPath))
{
fileNameList_Original.Add(fileName);
foreach (string text in File.ReadAllLines(fileName))
{
fullFileText_Original.Add(text);
//fileNameList_Original[counter]
}
}
Thanks for spotting the fileName instead of targetPath SGB! That was also a mistake I made!
I fixed the rest of the problems on my own now.
Related
The problem for a class asks to create an application to that reads numbers from a file to an array and calculates the total of the arrays values. But upon running the program I receive this error:
could not find file 'C\Users\daylo\Onedrive\Desktop\VisualStudio\Total Sales\Total Sales\bin\Debug\Sales/txt'.
I've tried copying and pasting the actual text file into the Program.cs but the same error appears. I figure the issue is due to the location of the file but I'm not sure how to troubleshoot it efficiently.
Here's the code:
public Form1()
{
InitializeComponent();
}
private void calcTotalBtn_Click(object sender, EventArgs e)
{
try
{
string[] allLines = File.ReadAllLines("Sales.txt");
double[] numbers = new double[allLines.Length];
int counter = 0;
double sum = 0;
foreach (string value in allLines)
{
numbers[counter] = Convert.ToDouble(value);
sum += numbers[counter];
outPutListBox.Items.Add(numbers[counter]);
counter++;
}
outPutListBox.Items.Add("\nTotal: " + sum.ToString("n"));
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
File.ReadAllLines("Sales.txt");
means to read the file in the current working directory. This is a terrible practice as you can only guarantee the current working directory if you explicitly change to it. As a best practice, always provide a full path and filename.
I have read a lot of answers on this issue, but none of them helps for me.
Now, it's been 5 years that I had C# and apperantly I've forgotten it all. But I like to get into the language again to use it for automation. So, here is the bit of code I already have:
{
string path = #"C:\Users\decraiec\Documents\Client Automated";
//In this folder I will find all my XML files that I just want to load in a textbox
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
//create a way to read and write the files
//go get the files from my harddrive
StreamReader FileReader = new StreamReader(path);
//make something readable for what you have fetched
StreamWriter FileWriter = new StreamWriter(textBox1.ToString());
int c = 0;
while (c == FileReader.Read())
{
string load = FileReader.ReadToEnd();//read every xmlfile up to the end
string stream = FileWriter.ToString();//make something readable
}
try
{
textBox1.Text = FileWriter.ToString();//what you have made readable, show it in the textbox
FileWriter.Close();
}
finally
{
if (FileReader != null)
{ FileReader.Close(); }
}
if (FileWriter != null)
{ FileWriter.Close(); }
}
}
If I run this code like this I'll get:
An unhandled exception of type 'System.UnauthorizedAccessException' occurred in mscorlib.dll
Additional information: Access to the path 'C:\Users\decraiec\Documents\Atrias Automated' is denied.
While I was hoping to see all the XML files in the textbox listed and clickable ( - although I need to insert the clickable code yet )
I've been looking in my folder and subfolder and files and I do have admin rights on everything. About the [ mscorlib.dll ] I have no clue where to find this.
Now if I wrap the StreamReader in a use ( var....;) VS doesn't recognizes it (red lines under the words) saying that I'm missing an instance of an object or something else of issue (just trying to glue the things together).
Could someone try to get me in the right direction please?
I think your path is a directory, not a file. Almost the exact same issue was addressed here: Question: Using Windows 7, Unauthorized Access Exception when running my application
What you can do is create a DirectoryInfo object on the path and then call GetFiles on it. For example:
DirectoryInfo di = new DirectoryInfo(directoryPath);
Foreach(var file in di.GetFiles())
{
string pathToUseWithStreamReader = file.FullName;
}
You need to use Directory.GetFiles to get any files residing in your "Client Automated" folder, then loop through them and load every single file into the stream.
var files = Directory.GetFiles(path);
foreach (var file in files)
{
var content = File.ReadAllText(file);
}
You can read more on it here:
https://msdn.microsoft.com/en-us/library/07wt70x2(v=vs.110).aspx
Also - in general, when working with files or directories like this, it's a good idea to programmatically check if they exist before working with them. You can do it like so:
if (Directory.Exists(path))
{
...
}
Or with files:
if (File.Exists(path))
{
...
}
im working on a project and what i try to do is to delete the
files in my folder.
but I get the error:
Could not find part of the path.
The problem is that the path have a ' which does make part of the path. Here is my code:
foreach (var a in attachments)
{
string[] files = System.IO.Directory.GetFiles(Server.MapPath("~/Files/'"+ a.FileName +"'"));
foreach (string pathfile in files)
{
System.IO.File.Delete(pathfile);
}
}
the result path is this:
'c:.....\Files\'14d75c4e-c25f-4288-9a75-08a359fe6d844.png'"
How can I solve this?
You don't need single quotes.
string[] files = System.IO.Directory.GetFiles(Server.MapPath("~/Files/"+ a.FileName));
This is because your code has extra (un needed) single quotes.
....MapPath("~/Files/'"+ a.FileName +"'"));
Change this line;
string[] files = System.IO.Directory.GetFiles(Server.MapPath("~/Files/'"+ a.FileName +"'"));
to
string[] files = System.IO.Directory.GetFiles(Server.MapPath(string.Format("~/Files/{0}", a.FileName));
Notice the change at the end of the code snippet(s).
Also, if I could suggest, wrap this in a Try / Catch (this would will help any future debugging as well).
Hope this helps.
Finally i have solved it.
the problem was the path and what i have done was little
different what i had before.
i have create a method to return the root path.
And then i have add it a simple variable and execute the
delete command.
Here is my code:
Method:
private string StorageRoot
{
get { return Path.Combine(System.Web.HttpContext.Current.Server.MapPath("~/Files/")); }
}
Delete Command:
foreach (var a in attachments)
{
var myfilename = a.FileName;
var filetoDelete = StorageRoot + myfilename;
System.IO.File.Delete(filetoDelete);
}
Hope this solution helps someone in the future.
Is possible to get all directories, subdirectories and files with recursion.
I do this because i want to increase my programming logic, and learn how recursion work.
I know to do that with this way:
string path = "D://";
string rezdir,newpath;
DirectoryInfo di = new DirectoryInfo(path);
DirectoryInfo[] dir = di.GetDirectories().ToArray();
for (int i = 0; i < di.GetDirectories().Length; i++)
{
Console.WriteLine(dir[i].ToString());
}
Console.WriteLine("\n\nChoose File: ");
rezdir = Console.ReadLine();
newpath = path + rezdir;
di = new DirectoryInfo(newpath);
dir = di.GetDirectories().ToArray();
for (int i = 0; i < di.GetDirectories().Length; i++)
{
Console.WriteLine(dir[i].ToString());
}
Console.ReadKey();
But i don't do that with recursion way, so ff someone can to do this, i'll be grateful to him.
Going by the code you posted - you seem to want some user interaction - so try something like this:
public static class RecursiveTest
{
public static string Foo(DirectoryInfo currentPath)
{
if (!currentPath.Exists) return string.Empty;
foreach (var directory in currentPath.EnumerateDirectories())
Console.WriteLine("Directory {0}", directory.Name);
foreach (var file in currentPath.EnumerateFiles())
Console.WriteLine("File {0}", file.Name);
while(true)
{
Console.WriteLine("Choose directory or file: ");
string chosenPath = Console.ReadLine();
string newPath = Path.Combine(currentPath.FullName, chosenPath);
if(Directory.Exists(newPath))
return Foo(new DirectoryInfo(newPath));
if(File.Exists(newPath))
return newPath;
Console.WriteLine("File {0} doesn't exist!", newPath);
}
}
}
And call with something like this:
class Program
{
static void Main(string[] args)
{
Console.WriteLine(RecursiveTest.Foo(new DirectoryInfo(#"d:\dev")));
Console.ReadLine();
}
}
HTH
I will avoid coding, because this is a valuable learning exercise. Try completing it yourself: once you do, you'll know that you understand recursion.
To be recursive, a method needs to call itself. Imagine that a method
public static void ShowDirectory(int indentationLevel, DirectoryInfo path)
is already written for you. This makes it easier to write the body:
Get all files in the directory, and print their names in the loop
Get all directories in the directory, and show their content at the next indentation level. You need another loop for that.
The first step is a simple exercise in writing loops. The second exercise becomes easy, too, because you can think of the ShowDirectory as pre-written.
Yeah, it's possible. But I do recommend that you first take a grasp of what recursion is. To put it simply, a recursion has a one-time executing part, and many-time executing part. That one time triggers the many-time part.
In this question, the one-time execution part might be to get the list of all directories beneath the root directory.
Then for each directory, you get all the sub-directories and files. This is the many-times part. However, to run a batch of codes many times, you need to bundle them into a callable routine, or procedure, or method, or function, whatever you call it. Just code bundle.
public void DoDirectories()
{
// one-time part; get a list of directories to start with.
List<string> rootDirectories = Directory.GetDirectories("c:\\").ToList();
foreach (string rootDirectory in rootDirectories)
{
GetSubdirectories(rootDirectory);
}
}
public List<string> GetSubdirectories(string parentDirectory)
{
List<string> subdirecotries = Directory.GetDirectories(
parentDirectory, "*.*", SearchOption.TopDirectoryOnly).ToList();
foreach (string subdirectory in subdirecotries)
{
GetSubdirectories(subdirectory); // recursing happens here
}
return subdirecotries;
}
I was wondering if there is a way to solve the issue I have with this code:
DriveInfo[] dDrives = DriveInfo.GetDrives();
foreach(DriveInfo dDrive in dDrives)
{
try
{
string sDrive = dDrive.ToString();
string[] sSearch = Directory.GetFiles(sDrive, sFile, SearchOption.AllDirectories);
foreach(string sResult in sSearch)
{
textBox2.Text = sResult + Environment.NewLine;
}
}
catch
{
}
}
When it comes across a file that isn't accessible because of permissions, it will goto the catch and end. What I need it to do is if it comes across a file it can't access, go back to the try block and continue searching. Any help is much appreciated, thanks!
EDIT:
Removed original answer as incorrect.
See: UnauthorizedAccessException cannot resolve Directory.GetFiles failure for some suggested resolutions to your problem.
The code you have should work, though you really should rethink your logic, using exceptions for flow control is plain wrong.
This will work, though not best practice:
string sDrive = dDrive.ToString();
try
{
string[] sSearch = Directory.GetFiles(sDrive, sFile, SearchOption.AllDirectories);
}
catch {}
foreach(string sResult in sSearch)
{
textBox2.Text = sResult + Environment.NewLine;
}
Where exactly are you accessing files? I only see a call to list file names (Directory.GetFiles), and listing of the file names returned.