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.
Related
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.
This question already has answers here:
C# replace string in string
(7 answers)
Closed 4 years ago.
I have a function in where I want to convert a string value C:\samplec#programs\Converter to C:\\samplec#programs\\Converter Note the differences. This is my function:
private string FilePathProcessor(string path)
{
char[] oriCharArray = path.ToCharArray;
List<char> oriCharList = new List<char>;
List<char> newCharList = new List<char>;
foreach (char item in oriCharArray)
{
oriCharList.Add(item);
}
foreach (char items in oriCharList)
{
if ((items != "\\"))
{
newCharList.Add(items);
}
else
{
newCharList.Add(items);
newCharList.Add(items);
}
}
string result = string.Join(",", newCharList.ToArray());
return result;
}
Of course this function serves my needs. But, I wonder if there is already an existing function in .Net which will take care of it. I am just cleaning up my code and checking for simpler and faster solution. Not going to reinvent the wheel if there is already a way.
Use String.Replace()
string path = #"C:\samplec#programs\Converter";
string output = path.Replace("\\", #"\\");
This question already has answers here:
How to filter Directory.EnumerateFiles with multiple criteria?
(8 answers)
Closed 7 years ago.
To loop through all files of one type, I do this :
foreach (string file in Directory.EnumerateFiles(folderPath, "*.txt"))
{
(code here)
}
Taken from how to read all files inside particular folder
Is there a way to have 2 tags other than making two loops? Like having all *.bmp, *.png...
NOTE : ANSWER I ACCEPTED DOWN HERE IS WAY MORE SIMPLE THAN THE ONE IN THE PROPOSED ANSWER, BUT BOTH WORKS.
You can concatenate two results like this
foreach (string file in Directory.EnumerateFiles(folderPath, "*.txt").Concat(Directory.EnumerateFiles(folderPath, "*.bmp")))
{
// (code here)
}
Or make it a function like so
IEnumerable<string> EnumerateFiles(string folderPath, params string[] patterns)
{
return patterns.SelectMany(pattern => Directory.EnumerateFiles(folderPath, pattern));
}
void Later()
{
foreach (var file in EnumerateFiles(".", "*.config", "*.exe"))
{
// (code here)
}
}
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);
}
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.");
}
}