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.
Related
I am trying to check to see if the file exists if it doesn't leave the textbox blank! it doesn't work
string[] filePaths = Directory.GetFiles(#"C:\TwinTable\LeftTableO0201", "*.*");
if (!File.Exists(filePaths.ToString()))
{
TboxLeftTable.Text = "";
}
else
{
TboxLeftTable.Text = System.IO.Path.GetFileName(filePaths[0]);
}
Well, one problem you have is that you are just trying to use ToString() on an array. Since Directory.GetFiles() returns an array of file names, you need to iterate over those files and check them one at a time. Something like this:
string[] filePaths = Directory.GetFiles(#"C:\TwinTable\LeftTableO0201", "*.*");
foreach (string curFilePath in filePaths)
{
if (!File.Exists(curFilePath))
{
TboxLeftTable.Text = "";
}
else
{
TboxLeftTable.Text = System.IO.Path.GetFileName(curFilePath);
}
}
Once your code is fixed you still have weird logic. If we take your logic and spell it out in a sentence it reads like this:
Get a list of files from a folder, then immediately check to see if the file(s) in that folder exist
I think what you want to do instead is:
Get a list of files from a folder, if one exists display the very first one's name in a textbox, if it does not, display nothing
If I am right, then your code would look like this:
// Gets all string file paths in a folder
// then grabs the first one, or null if there are none
string filePath = Directory.GetFiles(#"C:\TwinTable\LeftTableO0201", "*.*").FirstOrDefault();
// if the path is not null, empty or whitespace
if(!string.IsNullOrWhiteSpace(filePath)
{
// then get the filename and put it in the textbox
TboxLeftTable.Text = Path.GetFileName(filePath);
}
else
{
// There were no files in the folder so make the textbox empty
TboxLeftTable.Text = string.Empty;
}
This is the working code. Thanks for the help!
string[] filePaths = Directory.GetFiles(#"C:\TwinTable\LeftTableO0201", "*.*");
if (filePaths.Length > 0)
TboxLeftTable.Text = System.IO.Path.GetFileName(filePaths[0]);
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))
{
...
}
I currently have this method that can successfully quote-enclose a single CSV file but I am trying to loop through 600+ CSV files in a directory and perform the Quote Enclose method on each one. I am unsure how to do this effectively. Any feedback is appreciated.
Below is my code:
public void QuoteEnclosingCSV()
{
string fileNamePath = Path.GetTempPath() + #"\Reports\*.csv";
var stringBuilder = new StringBuilder();
foreach (var line in File.ReadAllLines(fileNamePath))
{
stringBuilder.AppendLine(string.Format("\"{0}\"", string.Join("\",\"", line.Split(','))));
}
File.WriteAllText(string.Format(fileNamePath, Path.GetDirectoryName(fileNamePath)), stringBuilder.ToString());
}
string marFolder = Path.GetTempPath() + #"\Reports\";
var dir = new DirectoryInfo(marFolder);
foreach (var file in dir.EnumerateFiles("*.csv"))
{
QuoteEnclosingCSV();
}
Below is the error I'm receiving:
Illegal characters in path.
My first step in unraveling this conundrum would be to guess what the error message is trying to tell me. My first guess would be that it's trying to say that the path has illegal characters in it. Did you stop to check what characters were in the path that you get the error on?
I'll show you:
C:\Users\YoungStamos\AppData\Local\Temp\\Reports\*.csv
That's the path you pass to File.ReadAllLines(). The single argument to that method is a path to one single file. You can't have an asterisk (*) in a filename in Windows, because it's a wildcard.
What you seem to be trying to do is pass a parameter to QuoteEnclosingCSV(). In this loop, you carefully list each file, but you never tell QuoteEnclosingCSV() about any of them.
foreach (var file in dir.EnumerateFiles("*.csv"))
{
QuoteEnclosingCSV();
}
This is more like what you want:
public void QuoteEnclosingCSV(string fileNamePath)
{
var stringBuilder = new StringBuilder();
foreach (var line in File.ReadAllLines(fileNamePath))
{
stringBuilder.AppendLine(string.Format("\"{0}\"", string.Join("\",\"", line.Split(','))));
}
// I don't know what string.Format() is meant to do here; I'm guessing your guess is
// as good as mine, so I'm eliminating it.
//File.WriteAllText(string.Format(fileNamePath, Path.GetDirectoryName(fileNamePath)), stringBuilder.ToString());
File.WriteAllText(fileNamePath, stringBuilder.ToString());
}
And then call it like this:
string marFolder = Path.Combine(Path.GetTempPath(), "Reports");
var dir = new DirectoryInfo(marFolder);
foreach (var fileInfo in dir.EnumerateFiles("*.csv"))
{
QuoteEnclosingCSV( fileInfo.FullName );
}
I'm using a code to show all startup items in listbox with environment variable "%appdata%
There is some errors in this code that I need help with....
Check code for commented errors
Is there any other solution but still using %appdata%?
This is the code:
private void readfiles()
{
String startfolder = Environment.ExpandEnvironmentVariables("%appdata%") + "\\Microsoft\\Windows\\Start Menu\\Programs\\Startup";
foldertoread(startfolder);
}
private void foldertoread(string folderName)
{
FileInfo[] Files = folderName.GetFiles("*.txt"); // HERE is one error "Getfiles"
foreach (var file in Directory.GetFiles(folderName))
{
startupinfo.Items.Add(file.Name); // here is another error "Name"
}
}
This line won't work because folderName is a string (and does not have a GetFiles method):
FileInfo[] Files = folderName.GetFiles("*.txt");
The second error is occurring because the file variable is a string containing the filename. You don't need to call file.Name, just try the following:
startupinfo.Items.Add(file);
I don't think you need the following line:
FileInfo[] Files = folderName.GetFiles("*.txt");
The foreach loop will generate what you need.
Secondly, the file variable is a string, so rather than calling:
startupinfo.Items.Add(file.Name);
...call instead:
startupinfo.Items.Add(file);
Finally, instead of a var type for your loop, you can use a string, and you can specify the file type filter:
foreach (string fileName in Directory.GetFiles(folderName, "*.txt"))
The string object doesn't have a GetFiles() method. Try this:
string startfolder = Environment.GetFolderPath(Environment.SpecialFolder.Startup);
string[] files = Directory.GetFiles(startfolder, "*.txt");
foreach (string file in files)
{
startupinfo.Items.Add(Path.GetFileNameWithoutExtension(file));
}
Path.GetFileNameWithoutExtension(file) returns just the file name instead of full path.
One option would be to do System.IO.Directory.GetParent() a few times. Is there a more graceful way of travelling a few folders up from where the executing assembly resides?
What I am trying to do is find a text file that resides one folder above the application folder. But the assembly itself is inside the bin, which is a few folders deep in the application folder.
Other simple way is to do this:
string path = #"C:\Folder1\Folder2\Folder3\Folder4";
string newPath = Path.GetFullPath(Path.Combine(path, #"..\..\"));
Note This goes two levels up. The result would be:
newPath = #"C:\Folder1\Folder2\";
Additional Note
Path.GetFullPath normalizes the final result based on what environment your code is running on windows/mac/mobile/...
if c:\folder1\folder2\folder3\bin is the path then the following code will return the path base folder of bin folder
//string directory=System.IO.Directory.GetParent(Environment.CurrentDirectory).ToString());
string directory=System.IO.Directory.GetParent(Environment.CurrentDirectory).ToString();
ie,c:\folder1\folder2\folder3
if you want folder2 path then you can get the directory by
string directory = System.IO.Directory.GetParent(System.IO.Directory.GetParent(Environment.CurrentDirectory).ToString()).ToString();
then you will get path as c:\folder1\folder2\
You can use ..\path to go one level up, ..\..\path to go two levels up from path.
You can use Path class too.
C# Path class
This is what worked best for me:
string parentOfStartupPath = Path.GetFullPath(Path.Combine(Application.StartupPath, #"../"));
Getting the 'right' path wasn't the problem, adding '../' obviously does that, but after that, the given string isn't usable, because it will just add the '../' at the end.
Surrounding it with Path.GetFullPath() will give you the absolute path, making it usable.
public static string AppRootDirectory()
{
string _BaseDirectory = AppDomain.CurrentDomain.BaseDirectory;
return Path.GetFullPath(Path.Combine(_BaseDirectory, #"..\..\"));
}
Maybe you could use a function if you want to declare the number of levels and put it into a function?
private String GetParents(Int32 noOfLevels, String currentpath)
{
String path = "";
for(int i=0; i< noOfLevels; i++)
{
path += #"..\";
}
path += currentpath;
return path;
}
And you could call it like this:
String path = this.GetParents(4, currentpath);
C#
string upTwoDir = Path.GetFullPath(Path.Combine(System.AppContext.BaseDirectory, #"..\..\"));
The following method searches a file beginning with the application startup path (*.exe folder). If the file is not found there, the parent folders are searched until either the file is found or the root folder has been reached. null is returned if the file was not found.
public static FileInfo FindApplicationFile(string fileName)
{
string startPath = Path.Combine(Application.StartupPath, fileName);
FileInfo file = new FileInfo(startPath);
while (!file.Exists) {
if (file.Directory.Parent == null) {
return null;
}
DirectoryInfo parentDir = file.Directory.Parent;
file = new FileInfo(Path.Combine(parentDir.FullName, file.Name));
}
return file;
}
Note: Application.StartupPath is usually used in WinForms applications, but it works in console applications as well; however, you will have to set a reference to the System.Windows.Forms assembly. You can replace Application.StartupPath by
Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location) if you prefer.
I use this strategy to find configuration and resource files. This allows me to share them for multiple applications or for Debug and Release versions of an application by placing them in a common parent folder.
Hiding a looped call to Directory.GetParent(path) inside an static method is the way to go.
Messing around with ".." and Path.Combine will ultimately lead to bugs related to the operation system or simply fail due to mix up between relative paths and absolute paths.
public static class PathUtils
{
public static string MoveUp(string path, int noOfLevels)
{
string parentPath = path.TrimEnd(new[] { '/', '\\' });
for (int i=0; i< noOfLevels; i++)
{
parentPath = Directory.GetParent(parentPath ).ToString();
}
return parentPath;
}
}
this may help
string parentOfStartupPath = Path.GetFullPath(Path.Combine(Application.StartupPath, #"../../")) + "Orders.xml";
if (File.Exists(parentOfStartupPath))
{
// file found
}
If you know the folder you want to navigate to, find the index of it then substring.
var ind = Directory.GetCurrentDirectory().ToString().IndexOf("Folderame");
string productFolder = Directory.GetCurrentDirectory().ToString().Substring(0, ind);
I have some virtual directories and I cannot use Directory methods. So, I made a simple split/join function for those interested. Not as safe though.
var splitResult = filePath.Split(new[] {'/', '\\'}, StringSplitOptions.RemoveEmptyEntries);
var newFilePath = Path.Combine(filePath.Take(splitResult.Length - 1).ToArray());
So, if you want to move 4 up, you just need to change the 1 to 4 and add some checks to avoid exceptions.
Path parsing via System.IO.Directory.GetParent is possible, but would require to run same function multiple times.
Slightly simpler approach is to threat path as a normal string, split it by path separator, take out what is not necessary and then recombine string back.
var upperDir = String.Join(Path.DirectorySeparatorChar, dir.Split(Path.DirectorySeparatorChar).SkipLast(2));
Of course you can replace 2 with amount of levels you need to jump up.
Notice also that this function call to Path.GetFullPath (other answers in here) will query whether path exists using file system. Using basic string operation does not require any file system operations.