C# Listing files without hidden files (Plus listing option) [duplicate] - c#

This question already has answers here:
C# - Get a list of files excluding those that are hidden
(8 answers)
Closed 7 years ago.
here is a code to list the files I've in a directory, then the user can type the file name to open the file.
public static void openFile()
{
// List files in FormatedDocuments directory
String[] showFiles = Directory.GetFiles("FormatedDocuments");
int filesList = showFiles.GetUpperBound (0) + 1;
const String folderToOpen = #"FormatedDocuments/";
Console.WriteLine ("Here is the list of files:");
for (int i = 0; i < filesList; i++) {
Console.WriteLine ("\tFile : " + Path.GetFileName (showFiles [i]));
}
// When listing is finished, ask the user to select the file he want to open
Console.WriteLine (#"Type the filename (With extension) you want to open:");
String userChoice = folderToOpen + Console.ReadLine ();
Process.Start (userChoice); // Loading with default application regarding the file extension
}
My questions are:
How to list only visible files in the selected directory? [DONE]
How to return in the console a number before each file, and ask the user to type this number instead of the full file name? [Waiting proposition]
I'm a beginner and try to learn by myself, don't be too "expert" in your solution please, I know my current code is not optimized, I try to do it step by step, but I accept your help about this code :)
Thank you for your answers.

I have found this:
This should work for you:
DirectoryInfo directory = new DirectoryInfo(#"C:\temp");
FileInfo[] files = directory.GetFiles();
var filtered = files.Select(f => f)
.Where(f => (f.Attributes & FileAttributes.Hidden) == 0);
foreach (var f in filtered) {
Debug.WriteLine(f);
}

Related

How to read all items on the Start menu

How can I get a list of all the shortcuts/programs in the start menu using C#?
I had to do this recently and surprisingly couldn't find a question for it anywhere on SO so thought I would share how I did it.
The following code reads the files from the special folder then LINQ to split the full pathname based upon the backslash character and takes the last element to get just the filename. It then splits the filename based upon the full stop (period) character and takes the first element to get the filename minus the extension.
Note the only difference between the All Users and Current User is the SpecialFolder name which is either CommonStartMenu or StartMenu.
Current User Start Menu
string startmenu = Environment.GetFolderPath(Environment.SpecialFolder.StartMenu);
IEnumerable<string> files = Directory.GetFiles(startmenu, "*.*", SearchOption.AllDirectories).Select(x => x.Split('\\').Last().Split('.').First());
foreach (var file in files)
{
Console.WriteLine(file);
}
Console.ReadKey();
All Users Start Menu
string startmenu = Environment.GetFolderPath(Environment.SpecialFolder.CommonStartMenu);
IEnumerable<string> files = Directory.GetFiles(startmenu, "*.*", SearchOption.AllDirectories).Select(x => x.Split('\\').Last().Split('.').First());
foreach (var file in files)
{
Console.WriteLine(file);
}
Console.ReadKey();

C# Checking to see if files exist in folder [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 3 years ago.
Improve this question
I have a For Each Loop container where I process files that arrive nightly. I have three user variables defined: FolderPath ("I:\Data Analytics\Referral"), FileName (blank) -- read only variables, FileExistsFlg -- ReadWriteVariables. The first two are strings and the last one is an int. I have added "using System.IO;" to my Namespaces.The value for the FileExistsFlg is 0 -- the default value when I added the variable.
Here is my C# code:
public void Main()
{
// TODO: Add your code here
String FilePath = Dts.Variables["User::FolderPath"].Value.ToString()
+ Dts.Variables["User::FileName"].Value.ToString();
if ( File.Exists(FilePath))
{
Dts.Variables["User::FileExistsFlg"].Value = 1;
}
MessageBox.Show(FilePath);
MessageBox.Show(Dts.Variables["User::FileExistsFlg"].Value.ToString());
Dts.TaskResult = (int)ScriptResults.Success;
}
The task executes, but it always returns a value of 0 when in fact there are files. I'm using MessageBox.Show(. . . .) to test the script.
The code works correctly if I provide a specific file name in the variable, but the file names will change every day. If I leave the variable blank, then it returns 0.
This doesn't strike me as rocket science and I'm mystified why it keeps returning a false value.
Thanks.
I am assuming you want to get all the files from a folder. You can use System.IO.Directory.GetFiles to do this:
string mypath = "C:/myfolder/";
string[] files = Directory.GetFiles(mypath);
You can then run through all the files like this:
foreach(string item in files){
if(item.Contains("my file name without the extension")){
//Do Something
}
}
-----------EDIT #1
string mypath = "C:/myfolder/";
string[] files = Directory.GetFiles(mypath);
if(!files.Length == 0){
foreach(string item in files){
//Run rest of code using the item
}
}else{}
the foreach statement's string variable contains the file path of the file.
-----------EDIT #2
If an error occurs at the first if statement saying that the "!" operator cannot be applied to integers, then instead put the foreach code into the else statement.
string mypath = "C:/myfolder/";
string[] files = Directory.GetFiles(mypath);
if(files.Length == 0){
//do nothing. No files are in the folder.
}else{
foreach(string item in files){
//Do something. Files are in the folder.
}
}
From my understanding of the question, inside the foreach statement would be the code to process and archive the file. The string called "item" should contain the path to the file.

copying files from one folder to another only if their file name is a in a specified text file c#

I need to copy files from one folder to another but only if their file name is also in a text file. The text file is set up like so
file1.jpg
file2.jpg
file3.jpg
etc
There are around one-million files to copy. I'm using C#.
What would the best way to go about this be? I'm not sure if I should first read all the file names from the text file and put them in to a list then possibly convert the list in to an array then maybe use the array somehow? Or maybe there's a better way to go about it?
I know how to read and write to files and how to copy from one source destination to another. I don't know how to filter out specific files when copying from one source destination to another though.
Any help is greatly appreciated.
Thank you.
The following code will help you the process you want
string source = #"C:\SourcePath\";
string destination = #"C:\DestinationPath\";
string[] strFiles = File.ReadAllText(#"C:\Filename.txt").Split(' ');
for (int i = 0; i < strFiles.Length; i++)
{
File.Copy(source + strFiles[i], destination + strFiles[i]);
}
If the text file is one line with million files name. Use this
string from = #"c:\from" , to =#"d:\to"; // source and destination
StreamReader file = new StreamReader(#"c:\list.txt"); // your files list
string total=file.ReadLine();
string[] tobecopied = total.Split(' ');
foreach(string fil in tobecopied)
{
if(File.Exists(from+#"\"+fil))
{
File.Copy(from+#"\"+fil,to+#"\"+fil);
}
else
{
MessageBox.Show(fil+"Not found ");
}
}
But if the text file have 1 line per 1 file , for example
FIle1.exe
File2.exe
use this
string from = #"c:\from" , to =#"d:\to"; // source and destination
StreamReader file = new StreamReader(#"c:\list.txt"); // your files list
string total="";
string temp="";
while((temp=file.ReadLine())!=null)
{
total+=temp+" ";
}
string[] tobecopied = total.Split(' ');
foreach(string fil in tobecopied)
{
if(File.Exists(from+#"\"+fil))
{
File.Copy(from+#"\"+fil,to+#"\"+fil);
}
else
{
MessageBox.Show(fil+"Not found ");
}
}
These ways also check for file existance.
Hope it works. If someone see error please edit it.

Remove file type from string [duplicate]

This question already has answers here:
Remove file extension from a file name string
(13 answers)
Closed 9 years ago.
I'm calling a list of strings from a server.
At the moment I'm getting the full name and file extension like:
Image1.jpg
image2.png
test_folder.folder
I have some code that relies on the knowing what the extension is, however I also need to access the name of the item I've selected with out the extension.
So far my two attempts have been the following:
_clickedFolder = listBox1.SelectedItem.ToString() - "folder";
_clickedFolder.Trim(new Char[] { '.folder' });
but neither of these work.
What is the correct way to take the file extension away and just have the file name display?
Use the Path class:
string fnWithoutExtension = Path.GetFileNameWithoutExtension(path);
or
string extension = Path.GetExtension(path);
You can try this:
string name = "set this to file name";
name = name.Substring(0,name.LastIndexOf('.'));
Try this;
private void listBox1_SelectionIndexChanged(object sender,EventArgs e)
{
string item = listBox1.SelectedItem.ToString();
int index = item.LastIndexOf('.');
if (index >= 0)//It's a valid file
{
string filename = item.Substring(0, index );
MessageBox.Show(filename);
}
else if (index == -1)//Not a valid file
{
MessageBox.Show("The selected file is invalid.");
}
}

Increment filename [duplicate]

This question already has answers here:
How would you make a unique filename by adding a number?
(22 answers)
Closed 8 months ago.
I want to create algorithm, to generate name for new file which I want to add to main directory.
All files in this directory must has unique name and start with "myFile"
What do you think about this algorithm ? Can I optimize it ?
string startFileName="myFile.jpg";
string startDirectory="c:\MyPhotosWithSubFoldersAndWithFilesInMainDirectory";
bool fileWithThisNameExists = false;
string tempName = null;
do
{
tempName = startFileName +"_"+ counter++ + Path.GetExtension(startFileName);
foreach (var file in Directory.GetFiles(startDirectory)
{
if (Path.GetFileName(tempName) == Path.GetFileName(file))
{
fileWithThisNameExists = true;
}
}
if (fileWithThisNameExists) continue;
foreach (var directory in Directory.GetDirectories(startDirectory))
{
foreach (var file in Directory.GetFiles(directory))
{
if (Path.GetFileName(tempName) == Path.GetFileName(file))
{
fileWithThisNameExists = true;
}
}
}
} while (fileWithThisNameExists);
If you are not worried about the rest of the file name (except the starting as "myFile", then you can simply create a GUID and concat it to the worg "myFile". This is the simplest way. The other way might be taking the syste ticks and add it as a string to the word "myFile".
If you construct your filenames so that they sort alphabetically
base000001
base000002
...
base000997
Then you can get a directory listing and just go to the end of the list to find the last file.
Be careful though: what happens if two instances of your program are running at the same time? There's a little window of opportunity between the test for the file existing and its creation.

Categories