Get Absolute Path of file in C# from file name [duplicate] - c#

This question already has answers here:
How to get a path to the desktop for current user in C#?
(2 answers)
Closed 3 years ago.
I have a File on my Desktop and I want to get the full Path of the File in my code, should it be on my Desktop or anywhere
My code is looking like this
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace GetFullPath
{
class Program
{
static void Main(string[] args)
{
string filename = "eMemoExpenseApproval.docx";
string fullFilePath = Path.Combine(Directory.GetCurrentDirectory(), filename);
Console.Write("Path : " + fullFilePath);
Console.Read();
}
}
}
Rather than get the full path from Desktop it shows the Path from Visual Studio, which is not suppose to be so, but i get this instead
Path : C:\Users\Administrator\Documents\Visual Studio 2017\Projects\GetFullPath\GetFullPath\bin\Debug\eMemoExpenseApproval.docx
Edit:
this works to get the Path of the file on Desktop
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace GetFullPath
{
class Program
{
static void Main(string[] args)
{
string filename = "eMemoExpenseApproval.docx";
string path = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
string fullFilePath = path +"/"+ filename;
Console.Write("Path : " + fullFilePath);
Console.Read();
}
}
}
Fine but How about other directories?

Directory.GetCurrentDirectory() actually returns the directory in which the application is executed.
If you know that the file is located in your Desktop, you can instead do something like this :
string fullFilePath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop, filename));

As I understand you want to search a limited set of folders for a named file. To do that declare a function like this:
IEnumerable<string> FindInMultipleFolders(string[] folders, string filename)
{
var result = new List<string>();
foreach (var folder in folders)
{
var dirs = Directory.GetFiles(folder, filename);
foreach (String dir in dirs)
{
result.Add(dir);
}
}
return result;
}
And call it with the file name and the folders to search like this:
FindInMultipleFolders(
new string[]
{
Environment.GetFolderPath(Environment.SpecialFolder.Desktop),
Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments),
#"C:\Some\Other\Folder\I\Would\Like\Searched"
},
"eMemoExpenseApproval.docx");
}
The file might be in multiple folders, so the function returns an IEnumerable<string>. FindInMultipleFolders only searches the passed folders, not subfolders. If you want subfolders to be searched you should add SearchOption.AllDirectories as a third parameter to GetFiles. Then you could search the whole hard drive with:
FindInMultipleFolders(
new string[]
{
#"C:\"
},
"eMemoExpenseApproval.docx");
}

Related

Get file names from azure blob storage

I'm using azure blobstorage in c#, is there a way, a method to get the list of files from a given specific folder?
like get all file names inside this url https://prueba.blob.core.windows.net/simem/UAL/Dato%20de%20archivo%20prueba%20No1/2022/1/16
i know that using container.GetBlobs() i would get all files but not from a specific folder
Just use
var results = await container.ListBlobsSegmentedAsync(prefix, true, BlobListingDetails.None, null, null, null, null);
You can get file names from a specific folder using BlobServiceClient and GetBlobs and by using below code in C# Console App and I followed Microsoft-Document and #Cindy Pau's answer:
using Azure.Storage.Blobs;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApp4
{
class Program
{
static void Main(string[] args)
{
string cs= "Connection String of Storage Account";
string f = "test";
BlobServiceClient b = new BlobServiceClient(cs);
string c = "pool";
BlobContainerClient containerClient =b.GetBlobContainerClient(c);
var bs= containerClient.GetBlobs(prefix: f);
foreach (var x in bs)
{
Console.WriteLine(x.Name);
Console.ReadLine();
}
}
}
}
In Storage Account of pool Container:
Now inside test Folder:
Output:
Press Enter after every line to get File names one by one.

How to handle a case when the hard disk drive letter is not the same when saved it to a text file?

in the constructor :
SaveLoadFiles.LoadFile(textBoxRadarPath, "radarpath.txt");
SaveLoadFiles.LoadFile(textBoxSatellitePath, "satellitepath.txt");
if (textBoxRadarPath.Text != "" || textBoxSatellitePath.Text != "")
{
if(!Directory.Exists(textBoxRadarPath.Text))
{
Directory.CreateDirectory(textBoxRadarPath.Text);
}
if (!Directory.Exists(textBoxSatellitePath.Text))
{
Directory.CreateDirectory(textBoxSatellitePath.Text);
}
btnStart.Enabled = true;
}
else
{
btnStart.Enabled = false;
}
the SaveLoadFiles class
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace Weather
{
public class SaveLoadFiles
{
public static void SaveFile(string contentToSave, string fileName)
{
string applicationPath = Path.GetFullPath(System.AppDomain.CurrentDomain.BaseDirectory); // the directory that your program is installed in
string saveFilePath = Path.Combine(applicationPath, fileName);
File.WriteAllText(saveFilePath, contentToSave);
}
public static void LoadFile(TextBox loadTo, string fileName)
{
string applicationPath = Path.GetFullPath(System.AppDomain.CurrentDomain.BaseDirectory); // the directory that your program is installed in
string saveFilePath = Path.Combine(applicationPath, fileName); // add a file name to this path. This is your full file path.
if (File.Exists(saveFilePath))
{
loadTo.Text = File.ReadAllText(saveFilePath);
}
}
}
}
when i used the application before and backed it up on my usb flash drive the second hard drive letter was D i had two hard disks : C and D and the project and the folders were on drive D.
now i backed up the project including the saved files but now my hard disks letters are C and E there is no D
but in the constructor when it's reading the text files the folders in the text files are D:....etc
but it should be E:
I'm checking if the folder exist or not and then if not creating it but it's trying to create the folder on drive D and D is not existing.
You are reading contents of a data file that has a file path that no longer exists.
The solution is to edit those data files: "radarpath.txt" and "satellitepath.txt" to have the proper path.
An application would normally provide a UI for selecting the folder to use, rather than saving a hardcoded path in a datafile. What you could do is use FileDialog to prompt the user for the directories to use if they don't exist.

Moving all unknown and future folders to specific folder

I am trying to create script for my terminal server, which will move all folders with their contents, created in the wrong place. I don't know which names these folders will have. As I noticed, moving folders in C# is a problem for some reason. Can someone help me with my code? It just deleting my test folders and nothing moves.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
using Microsoft.VisualBasic.FileIO;
namespace ConsoleApp1
{
public class Programm
{
public static void Main()
{
string root = #"C:\Users\user1\Desktop";
string[] subdirectoryEntries = Directory.GetDirectories(root);
string destDirname = #"D:\confiscated";
foreach (string path in subdirectoryEntries)
{
FileSystem.MoveDirectory(path, destDirname, true);
}
}
}
}
This is how to do it:
string startPath = #"YOURSTARTPATH";
string endPath = #"YOURENDPATH";
foreach (string directory in Directory.GetDirectories(startPath))
{
Directory.Move(directory, Path.Combine(endPath, Path.GetFileName(directory)));
}
This way, you will use the already provided by the framework classes to work with directories.
No need to include Microsoft.VisualBasic.FileIO

Deleting an specified string by user in an array?

What i want to do here was getting an string input from the user and if that string input is in the array i want to delete it from the file (all the items in the array is actual files in my computer that got scanned at the start of the program and become one array) is there a way to do that without foreach?
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Diagnostics;
using System.IO;
using System.Threading;
string typed = null;
string loc = AppDomain.CurrentDomain.BaseDirectory;
if (!Directory.Exists(loc + #"\shortcuts"))
{
Directory.CreateDirectory(loc + #"\shortcuts");
}
string[] directory = Directory.GetFiles(loc + #"\shortcuts");
foreach (var filed in directory)
{
File.Move(filed, filed.ToLowerInvariant());
}
string[] file = Directory.GetFiles(loc + #"\shortcuts").Select(System.IO.Path.GetFileNameWithoutExtension).ToArray();
foreach (string dir in directory)
{
}
if (typed == "exit") System.Environment.Exit(0);
//other ifs here
else if (typed == "rem")
{
//Console.WriteLine("\nNot available at the moment\n");
////add this command
Console.WriteLine("\nWhich program entry do you wish to erase?\n");
typed = Console.ReadLine().ToLower();
if (file.Any(typed.Contains))
{
File.Delete(file.Contains(typed)); //this is the broken part and i don't know how i can get the stings from there
Console.WriteLine("hi");
}
else Console.WriteLine("\n" + typed + " is not in your registered programs list.\n");
}
Expected result was getting rid of the typed program in the folder and actual results was just an error code.
You are storing only the file name in the array, not its complete path or extension. You need to change this, and allow it to store FileName with extension.
string[] file = Directory.GetFiles(loc + #"\shortcuts").Select(System.IO.Path.GetFileName).ToArray();
and then, you need to change the If condition as follows.
if (file.Contains(typed))
{
File.Delete(Path.Combine(loc + #"\shortcuts",typed));
Console.WriteLine("hi");
}
In this Scenario, user would need to input the file name with extension.
If you want the User to input only the filename(without extension, as in your code), then, you could run into a situation where there could be two files with different extension.
"test.jpg"
"test.bmp"
Update
Based on your comment that you cannot store extensions, please find the updated code below. In this scenario, you do not need to change the array. Since you are only storing lnk files, you can append the extension to the file name to complete the path during Path.Combine.
if (file.Contains(typed))
{
File.Delete(Path.Combine(loc , #"shortcuts",$"{typed}.lnk"));
Console.WriteLine("hi");
}

"File.Exists" does not exist

I created this class "XML_Toolbox" that could be used by any of my forms to perform any of the key XML actions that i am going to be using repeatedly. So with that being said, here is that class' code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
using System.Windows.Forms;
namespace Personal_Finance_Manager
{
class XML_toolbox
{
public static void createFile (string filename, string filePath)
{
string createPath = filePath + #"\" + filename + ".txt";
if (file.exists(createPath))
{
StreamWriter outfile = new StreamWriter(createPath, true);
}
else
{
MessageBox.Show("This file already exists!!! Please choose another name!");
}
}
}
}
all the individual parts were working when called from another form up until i added the:
if (file.exists(createPath)) {}
IF statement.
Now i am getting the
The name "file" does not exist in the current context
error. I have the
using System.IO;
what else am i missing?
Thanks!
Class name is File not file, method name is Exists. C# is case-sensitive.
It's called File, not file.
File.Exists()

Categories