Path.Combine() C# - c#

So on my previous question (C# Only File NAMES in ListBox) I asked how to show only the file names.I got that to work. Then I encountered another problem: I could not load whats in the directory because there is no way to. A user told me
"
You either need to use a Dictionary datasource for your ListBox (with the key being the file name and the value being that path) See this answer for an idea of what I mean. Or you need to rebuild the path in your
IndexChange function (using Path.Combine() )
"
And me being me, I had no clue what he meant. So I came back for more help. I have not put any code as I don't know how to.

https://msdn.microsoft.com/it-it/library/fyy7a5kt(v=vs.110).aspx
string folder = #"C:/Aatrox";
private void ListBox1_SelectedIndexChanged(object sender, EventArgs e)
{
var fileName = (string)ListBox1.SelectedItem;
textEditorControl1.Text = File.ReadAllText(Paht.Combine(folder, fileName));
}
private void FlatButton3_Click(object sender, EventArgs e)
{
ListBox1.Items.Clear();
string[] txtfiles = Directory.GetFiles(folder, "*.txt");
string[] luafiles = Directory.GetFiles(folder, "*.lua");
foreach (var item in txtfiles)
{
ListBox1.Items.Add(Path.GetFileName(item));
}
foreach (var item in luafiles)
{
ListBox1.Items.Add(Path.GetFileName(item));
}
}

If I understand correctly, you want a List of file names from a certain directory. You want to use Directory.EnumerateFiles to get each file in the directory. Path.Combine only combines a directories path, for modularity and use on other PC's mainly, such as Path.Combine(Environment.CurrentDirectory, "Hello").

Related

How to search contain in name File C#

I want to search for the characters in Name file of the Directory. If the content is different from the results found, delete the file. I've tried the code below:
private void btnStart_Click(object sender, EventArgs e)
{
FileWithFilter(Parth, "Abc123");
}
private void FileWithFilter(string folderName, string filesToExclude)
{
DateTime dateTime = DateTime.Now;
DirectoryInfo dir = new DirectoryInfo(folderName);
foreach (FileInfo fi in dir.GetFiles())
{
if (!fi.Name.Contains(filesToExclude))
{
fi.delete();
}
}
}
It works, but if the file in Directory is more than 10 or 11(file), code can't run correctly!
please tell me any better way or other solution.
I would propose to save all files which should be deleted in a list and then delete them afterwards. It is not recommendd to manipulate the list you are iterating over.
private void FileWithFilter(string folderName, string filesToExclude)
{
List<string> filesToBeDeleted = Directory.GetFiles(folderName).Where(m => !m.Contains(filesToExclude)).ToList();
filesToBeDeleted.ForEach(m => File.Delete(m));
}

How to get all the files inside a folder?

In my program I have a treeview and a folderbrowser and a datagridview. The user uses the folder browser to choose a folder which contains bunch of shows which all have different seasons. My program displays the folders for the shows and the season folders inside them in the treeview and each time the select a folder from treeview I want it to display all the files inside that folder. I am currectly using this code:
public void fileProcessDirectory(string targetDirectory, string Name)
{
string[] fileEntries = Directory.GetFiles(targetDirectory);
foreach (string fileName in fileEntries)
{
FileProcessFile(fileName);
}
string[] subdirectoryEntries = Directory.GetDirectories(targetDirectory);
foreach (string subdirectory in subdirectoryEntries)
{
fileProcessDirectory(subdirectory, Name);
break;
}
}
public void FileProcessFile(string path)
{
dataGridView.Rows.Add(path, "New");
}
it shows the files inside the first sub folder that I have. it used to show all the files inside all the folders so I added a break and now it shows the first 3 files and stops there. So I want it to display the files inside the selected subfolder not all the sub folders.
You can try to modify your function as this:
public void FileProcessDirectory(string targetDirectory, string subfolder)
{
// this adds files
foreach (string fileName in Directory.GetFiles(targetDirectory))
{
FileProcessFile(fileName);
}
// if we pass subfolder as empty then nothing happens
if(string.IsNullOrEmpty(subfolder)) return;
// here we find our subfolder and display files for it
FileProcessDirectory(Directory.GetDirectories(targetDirectory).Where(d => d == targetDirectory + "\\" + subfolder).ToArray()[0], null);
}
And the ussage example:
FileProcessDirectory(Directory.GetParent(Directory.GetCurrentDirectory()).FullName, "Debug");
Please correct my understanding if I'm wrong:
user select the folder, then on treeview select the season then they should see in the data grid view all the files inside, correct ?
I implemented in this way
treeView1.NodeMouseDoubleClick += new TreeNodeMouseClickEventHandler(treeView1_NodeMouseClick);
if user double click on the treenode it shows all the files inside in the data grid:
void treeView1_NodeMouseClick(object sender, TreeNodeMouseClickEventArgs e)
{
if (treeView1.SelectedNode != null)
{
dataGridView1.Rows.Clear();
string[] fileEntries = System.IO.Directory.GetFiles(treeView1.SelectedNode.Text);
foreach (string fileName in fileEntries)
{
dataGridView1.Rows.Add(Path.GetFileName(fileName));
}
}
}
I guess the problem before maybe caused by the dataGrid not clearing the old files. Hope it helps.

Load text file using command args

I am currently writing a text editor program, however I have run into a problem.
I am attempting to allow the user to open a file with my program by double-clicking it, which is achieved by setting the default program. I have been told that this sends the program the filepath as a command argument.
I am using it like this:
private void formMain_Load(object sender, EventArgs e)
{
string[] args = System.Environment.GetCommandLineArgs();
string filePath = args[1];
addTab();
getFontCollection();
setFontSizes();
getCurrentDocument.Text = (File.ReadAllText(filePath));
}
However, I consistently get the following error:
An unhandled exception of type 'System.NotSupportedException' occurred in mscorlib.dll
Additional information: The given path's format is not supported.
If someone would please direct me to fixing this, it would be greatly appreciated.
By the way, the entire source code is located on Github, github.com/Criticaldiamonds/asys
EDIT
According to MSDN, the first argument is the program itself, followed by user-specified arguments. Therefore,
args[0] = the program
args[1] = "C:\users\Giovanni\Desktop\Hello.txt" (w/o quotes ofc)
Because the VS debugger escapes characters, the value of args[1] in the debugger is "C:\\users\\Giovanni\\Desktop\\Hello.txt"
You should use the Methods on the System.IO.Path Class
private void Form1_Load(object sender, EventArgs e)
{
var args = System.Environment.GetCommandLineArgs();
// using linq here reduces that array count check then extract
var argPath = args.Skip(1).FirstOrDefault();
if (!string.IsNullOrEmpty(argPath))
{
// Your .LoadFile(...) method requires a full path
var fullPath = Path.GetFullPath(argPath);
/* this part isn't needed unless you want to ensure the directory exists... but if it doesn't exist you can't open it anyway
var dirPath = Path.GetDirectoryName(fullPath);
if (!Directory.Exists(dirPath))
Directory.CreateDirectory(dirPath);
*/
/* this isn't needed since you are using the full path
Directory.SetCurrentDirectory(dirPath);
*/
addTab();
getFontCollection();
setFontSizes();
getCurrentDocument.LoadFile(fullPath, RichTextBoxStreamType.PlainText);
}
}
I managed to solve the problem! Thank you to everyone who left comments, they really did help!
By messing around with directory settings, I ended up with the following code, which correctly loads the test file!
private void formMain_Load(object sender, EventArgs e)
{
string[] args = System.Environment.GetCommandLineArgs();
string dirPath = args[1];
string fileName = "";
fileName = Path.GetFileName(dirPath);
dirPath = dirPath.Substring(3);
dirPath = Path.GetFullPath(dirPath);
if (dirPath.Contains('\\')) dirPath = dirPath.Substring(0, dirPath.LastIndexOf('\\'));
Directory.SetCurrentDirectory(dirPath);
addTab();
getFontCollection();
setFontSizes();
getCurrentDocument.LoadFile(dirPath + '\\' + fileName, RichTextBoxStreamType.PlainText);
}

Having problems deleting all files in a directory, then the directory itself

I am trying to delete a directory & all it's contents when I tap on a ContextMenu's MenuItem. However I seem to be running into to issues, as the files/directory aren't being deleted.
However I am not running into any errors, it just doesn't seem to work.
Here's my code so far:
private void gridSessionDelete_Tap(object sender, System.Windows.Input.GestureEventArgs e)
{
var item = (((sender as MenuItem).Parent as ContextMenu).Owner as Grid);
var title = (TextBlock)item.FindName("Title");
string directory = title.Text;
var appStorage = IsolatedStorageFile.GetUserStoreForApplication();
string[] fileList = appStorage.GetFileNames(directory + "\\*");
foreach (string file in fileList)
{
appStorage.DeleteFile(directory + "\\" + file);
}
appStorage.DeleteDirectory(directory);
bindList();
}
does anyone have any help on what I am doing wrong?
Thanks all help is appreciated!
Well, I can see a couple of places, where the error could be.
First, this line:
var item = (((sender as MenuItem).Parent as ContextMenu).Owner as Grid);
As you know, when you cast types with as keyword, the result might be null and no exception is thrown.
Second, and IMO most important:
This line:
string[] fileList = appStorage.GetFileNames(directory + "\\*");
That won't find anything. You should use "." (star-point-star) instead of "*"(star) in search request.
Also, when you work with IsolatedStorage, use using keyword, like:
using (IsolatedStorageFile myIsolatedStorage = IsolatedStorageFile.GetUserStoreForApplication())
{
// your code
}
Does the code actually execute? Do breakpoints get hit? If so here is code that I use to delete all files in a directory. It does work for me. The main difference I see is in the DeleteFile method.
var storage = IsolatedStorageFile.GetUserStoreForApplication();
if (storage.DirectoryExists(directoryName))
{
foreach (var oldFile in storage.GetFileNames(string.Concat(directoryName, "\\*")))
{
storage.DeleteFile(Path.Combine(directoryName, oldFile));
}
}

"Could not find part of the path" error when copying a file

I've googled about this all over the Internet and still haven't found a solution. As an ultimate try, I hope someone can give me an exact answer.
I get that error when I try to copy a file from a directory to another in an File Explorer I'm trying to do on my own. It has a treeview control to browse for directories and a listview control to display the contents of the directory. This is how the code would look like, partially:
private void copyToolStripMenuItem_Click(object sender, EventArgs e)
{
sourceDir = treeView1.SelectedNode.FullPath;
for (int i = 0; i < listView1.SelectedItems.Count; ++i)
{
ListViewItem l = listView1.SelectedItems[i];
toBeCopied[i] = l.Text; // string[] toBeCopied, the place where I save the file names I want to save
}
}
private void pasteToolStripMenuItem_Click(object sender, EventArgs e)
{
targetDir = treeView1.SelectedNode.FullPath;
try
{
for (int i = 0; i < toBeCopied.Length; ++i)
{
File.Copy(sourceDir + "\\" + toBeCopied[i], targetDir + "\\" + toBeCopied[i], true);
refreshToolStripMenuItem_Click(sender, e);
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message + Environment.NewLine + ex.TargetSite);
}
}
The place where I got the error is at File.Copy(sourceDir + "\\" + toBeCopied[i] ....
I've read that it could be something that has to do with the mapping of devices, but I don't really know what that is.
Can you take a look at the Path.Combine method on MSDN? This will help make sure all your entire path doesn't have extra \'s where they shouldn't be.
i.e. Path.Combine(sourceDir, toBeCopied[i])
If you are still getting an error, let me know what the value if the above.
Does the target path up to the file name exist? File.Copy() will not create any missing intermediate path, you would need to do this yourself. Use the debugger to see both the source and target paths you are creating and make sure the source exists and the target exists at least up to the parent of the target file.
You do not show where toBeCopied is created. It looks like you are probably running past the end of the values that are set in the click event, and trying to copy a bunch of files with empty names.
You should add this to the beginning of your click event
toBeCopied = new string[listView1.SelectedItems.Count];
Also (as others have noted) instead of
sourceDir + "\\" + toBeCopied[i]
you should use
Path.Combine(sourceDir, toBeCopied[i])
Assuming both sourceDir and targetDir exist (which you can and should check), you might be doubling up a trailing \. When building paths, you should use Path.Combine.
File.Copy(Path.Combine(sourceDir, toBeCopied[i]), Path.Combine(targetDir, toBeCopied[i]), true);
Borrowing from Henk's loop, but I'd add the file & directory checks, since it is the path not found errors that need checking/creating that the OP has the problem with.
for (int i = 0; i < toBeCopied.Length; ++i)
{
string sourceFile = Path.Combine(sourceDir, toBeCopied[i]);
if(File.Exists(sourceFile))
{
string targetFile = Path.Combine(targetDir, toBeCopied[i]);
if(!Directory.Exists(targetDir))
Directory.CreateDirectory(targetDir);
File.Copy(sourceFile, targetFile, true);
}
refreshToolStripMenuItem_Click(sender, e)
}

Categories

Resources