DirectoryInfo di = new DirectoryInfo(#"c:\windows\temp");
Here I want to replace c:\ with the current drive on which the user is operating windows.
Is it possible to do that?
In .net you ought to use Path.GetTempPath to get a temporary path:
https://learn.microsoft.com/en-us/dotnet/api/system.io.path.gettemppath?view=net-7.0&tabs=windows
Both Environment.GetEnvironmentVariable("SystemRoot") and Environment.GetEnvironmentVariable("windir") should give you the path in form of "driveLetter:\\Windows"
So you can do:
DirectoryInfo di = new DirectoryInfo(Environment.GetEnvironmentVariable("SystemRoot"));
For the difference between "SystemRoot" and "windir" see:
https://superuser.com/questions/638321/what-is-difference-between-windir-and-systemroot
DirectoryInfo di2 = new DirectoryInfo(Environment.GetEnvironmentVariable("SystemRoot"));
string path = Convert.ToString(di2);
DirectoryInfo di = new DirectoryInfo( path + #"\temp");
I figured it out. Here is the corrected code.
Related
I am creating a new folder in documents and after that I want to write a file to it. The problem is, is that the folder I create is 'read only'. So I can't add a file to it. I can't fix it.
What I have now:
string target_path = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), "data");
Directory.CreateDirectory(target_path);
var di = new DirectoryInfo(target_path);
di.Attributes &= ~FileAttributes.ReadOnly;
I also made my program startup as administrator but that doesn't make any difference.
Edit
When trying to store a file inside the folder I get the following error:
System.UnauthorizedAccessException: 'Access to the path "xxxx"' is denied.'
try explicitly set permissions.
string target_path = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), "data");
DirectorySecurity securityRules = new DirectorySecurity();
securityRules.AddAccessRule(new FileSystemAccessRule("Users",FileSystemRights.FullControl, AccessControlType.Allow));
DirectoryInfo di = Directory.CreateDirectory(target_path, securityRules);
I am currently working to a Windows 10 UWP project and I keep getting the following exception:
Unable to cast object of type 'System.IO.FileSystemInfo[]' to type 'System.Collections.Generic.IEnumerable`1[System.IO.FileInfo]'.
and this is the code which throws it:
DirectoryInfo dirInfo = new DirectoryInfo(path);
FileInfo[] files = dirInfo.GetFiles(path);
path is a valid one, i verified it several times, I do not know why I am getting this exception. Can the DirectoryInfo class still be used in a UWP application or should I use an equivalent one ?
The DirectoryInfo class is applicable for UWP. However, it has a lot of limitations. Such as whether the path is valid. For more detail you could refer to Skip the path: stick to the StorageFile.
It throw Second path fragment must not be a drive or UNC name exception when I passed path parameter. I found the following description.
The search string to match against the names of files. This parameter can contain
a combination of valid literal path and wildcard (* and ?) characters (see Remarks),
but doesn't support regular expressions. The default pattern is "*", which returns
all files.
So I modify the searchPattern like the following, it works well.
string root = Windows.ApplicationModel.Package.Current.InstalledLocation.Path;
string path = root + #"\Assets\Media";
DirectoryInfo dirinfo = new DirectoryInfo(path);
FileInfo[] files = dirinfo.GetFiles("head.*");
I do not know why I am getting this exception. Can the DirectoryInfo class still be used in a UWP application or should I use an equivalent one ?
The best practice to query files in UWP is to use folder picker to select a folder and enumerate all the files with GetFilesAsync method. For example:
var picker = new Windows.Storage.Pickers.FolderPicker();
picker.SuggestedStartLocation = Windows.Storage.Pickers.PickerLocationId.PicturesLibrary;
picker.FileTypeFilter.Add("*");
picker.ViewMode = Windows.Storage.Pickers.PickerViewMode.Thumbnail;
var folder = await picker.PickSingleFolderAsync();
if(folder != null)
{
StringBuilder outputText = new StringBuilder();
var query = folder.CreateFileQuery();
var files = await query.GetFilesAsync();
foreach (StorageFile file in files)
{
outputText.Append(file.Name + "\n");
}
}
it is my path example E:\test\img\sig.jpg
I want to get E:\test\img to create directory
i try split but it be img
so I try function Directory.CreateDirectory and the path is E:\test\img\sig.jpg\
say me a ideas?
The recommended way is to use Path.GetDirectoryName():
string file = #"E:\test\img\sig.jpg";
string path = Path.GetDirectoryName(file); // results in #"E:\test\img"
Use Path.GetDirectoryName which returns the directory information for the specified path string.
string directoryName = Path.GetDirectoryName(filePath);
The Path class contains a lot of useful methods for path handling, which are more reliable than manual string manipulation:
var directoryComponent = Path.GetDirectoryName(#"E:\test\img\sig.jpg");
// yields `E:\test\img`
For completeness, I'd like to mention Path.Combine, which does the opposite:
var dirAndFile = Path.Combine(#"E:\test\img", "sig.jpg");
// no more checking for trailing slashes, hooray!
To create the directory, you can use Directory.Create. Note that it is not necessary to check if the directory exists first.
You can try this code to find the directory name.
System.IO.FileInfo fi = new System.IO.FileInfo(#"E:\test\img\sig.jpg");
string dirname = fi.DirectoryName;
and to create the directory
Directory.CreateDirectory(dirname );
Another solution can be :
FileInfo f = new FileInfo(#"E:\test\img\sig.jpg");
if (f.Exists)
{
string dirName= f.DirectoryName;
}
How can I set the initial directory to be where my test data exists?
var relPath = System.IO.Path.Combine( Application.StartupPath, "../../" )
dlg.Title = "Open a Credit Card List";
dlg.InitialDirectory = relPath ;
The default directory it opens up to is where the .exe exists: Project2\Project2\bin\Debug
I want it to open up by default in the Project2 folder where my test data exists. But it does not allow me to move up a parent directory. How do I get around this?
You can use Directory.GetParent(string path)
string relPath = Directory.GetParent(Application.StartupPath).Parent.FullName;
Or using DirectoryInfo
DirectoryInfo drinfo =new DirectoryInfo(path);
DirectoryInfo twoLevelsUp =drinfo.Parent.Parent;
dlg.InitialDirectory = twoLevelsUp.FullName;;
To convert your relative path to an absolute path you can use Path.GetFullPath()
var relPath = System.IO.Path.Combine(Application.StartupPath, #"\..\..");
relPath = Path.GetFullPath(relPath);
dlg.InitialDirectory = relPath;
Alternatively if you wish to change the working directory to your test data:
Directory.SetCurrentDirectory(relPath);
More information:
http://msdn.microsoft.com/en-us/library/system.io.path.getfullpath.aspx
http://msdn.microsoft.com/en-us/library/system.io.directory.setcurrentdirectory.aspx
My intention is for my application to run on windows and linux.
The application will be making use of a certain directory structure e.g.
appdir/
/images
/sounds
What would be a good way of handling the differences in file(path) naming differences between windows and linux? I don't want to code variables for each platform. e.g. pseudo code
if #Win32
string pathVar = ':c\somepath\somefile.ext';
else
string pathVar = '/somepath/somefile.ext';
You can use the Path.DirectorySeparatorChar constant, which will be either \ or /.
Alternatively, create paths using Path.Combine, which will automatically insert the correct separator.
How about using System.IO.Path.Combine to form your paths?
Windows example:
var root = #"C:\Users";
var folder = "myuser";
var file = "text.txt";
var fullFileName = System.IO.Path.Combine(root, folder, file);
//Result: "C:\Users\myuser\text.txt"
Linux example:
var root = #"Home/Documents";
var folder = "myuser";
var file = "text.txt";
var fullFileName = System.IO.Path.Combine(root, folder, file);
//Result: "Home/Documents/myuser/text.txt"
If you're using Mono. In the System.IO.Path class you will find:
Path.AltDirectorySeparatorChar
Path.DirectorySeparatorChar
Hope this helps!