Using "~" in a path resolves as C:\ - c#

I'm trying to implement a server control that frobs a couple of files inside the web directory of an ASP.NET site. I'm using VS Web Dev Express 2008 as my IDE. When I call HttpContext.Current.Request.ApplicationPath to get a path to the web root so I can find those files, it returns C:. What the heck?
Absolute paths work just fine, but I'd like to be able to feed the server control a relative directory and just let it do it's thing. What have I done wrong?
public String Target
{
get { return _target; }
set
{
if (value.StartsWith("~"))
{
// WTF? Gives me C:\? Why?
_target = HttpContext.Current.Request.ApplicationPath +
value.Substring(1);
}
else
{
_target = value;
}
}
}
private String _target;
protected override void Render(HtmlTextWriter writer)
{
HtmlControl wrapper = new HtmlGenericControl("div");
int fileCount = 0;
try
{
DirectoryInfo dir = new DirectoryInfo(_target);
foreach (FileInfo f in dir.GetFiles())
{
fileCount++;
a = new HtmlAnchor();
a.Attributes.Add("href", f.FullName);
a.InnerHtml = f.Name;
wrapper.Controls.Add(a);
}
}
catch (IOException e)
{
throw e;
}
Controls.Add(wrapper);
base.Render(writer);
}

This might be because it's using the development web server, which can just serve files from any directory on your hard drive. It doesn't have any specific root. Can you run your project under IIS (assuming your version of windows supports it), and see if you get the same results?
To get rid of the problem completely you could just hard code the path you want to look at in your web.config and go around any problems with what Request.ApplicationPath is returning.
[EDIT]
Just found out you can use
HTTPContext.Current.Request.ServerVariables("APPL_PHYSICAL_PATH")
to return the path of your application, on the hard disk. I'm pretty sure that's what you are looking for. If that's not right, check out all the other ServerVariables to see if you can get what you are looking for.

How about this:
Server.MapPath(ResolveUrl("~/filename"))
There's also information on a page TLAnews.com titled, Understanding Paths in ASP.NET.

The ADME Developer's Kit may be what you need if you are trying to get the directory at design time.

Related

UWP Parse folder from absolute or relative path

I want to parse a folder that the user can choose.
But if I understand, absolute paths are not allowed in UWP because the disks are not the same following the media (xbox, windows phone, windows desktop, ...) ?
So, I have a class called Parser that can parse the path that the user picks but now, only the current folder can be parsed.
This doesn't work :
Parser parser = new Parser(#"C:\a\b\c");
parser.createTreeView(tree);
Help me please. Thank you in advance.
EDIT : This is my Parser class =>
public TreeViewItem Parse(DirectoryInfo directoryInfo)
{
try
{
var directoryNode = new TreeViewItem { Header = directoryInfo.Name };
Convention convention = new Convention();
foreach (var directory in directoryInfo.GetDirectories())
{
directoryNode.Items.Add(Parse(directory));
System.Diagnostics.Debug.WriteLine("test : " + directory.Name);
}
foreach (var file in directoryInfo.GetFiles())
{
if (file.Name.Contains(EConvention.INSTALL))
{
listFiles.Add(file.FullName);
}
TreeViewItem item = new TreeViewItem
{
Header = Path.GetFileNameWithoutExtension(file.FullName),
Tag = file.FullName
};
directoryNode.Items.Add(item);
}
return directoryNode;
}
catch (System.UnauthorizedAccessException e)
{
//MessageDialog dialog = new MessageDialog(""+e.Message);
dialogAsync(e.Message);
return new TreeViewItem();
}
}
public void CreateTreeView(TreeView tree)
{
DirectoryInfo dir = new DirectoryInfo(pathToParse);
System.Diagnostics.Debug.WriteLine("dir exists ? "+dir.Exists);
if (dir.Exists)
{
System.Diagnostics.Debug.WriteLine("dir existe");
TreeViewItem root = new TreeViewItem() { Header = dir.Name };
root.Tag = dir;
tree.Items.Add(Parse(dir));
}
}
UWP apps do not have permission to access all files on the device. Apps can access certain file system locations by default. Apps can also access additional locations through the file picker, or by declaring capabilities. For more info, please see File access permissions
Although, we can use DirectoryInfo in UWP apps, but it can only work with the folders that UWP apps can access by default such as the install directory and local folder etc. Most types in the System.IO namespaces for UWP apps have the similar limitation. While dealing with files or folders in UWP, one important rule is Skip the path: stick to the StorageFile.
You can use a Folder​Picker to let the user choose a folder and then add it to your app's FutureAccessList or MostRecentlyUsedList to keep track of it. You can learn more about using these lists in How to track recently-used files and folders. After this, you will be able to retrieve the StorageFolder from FutureAccessList or MostRecentlyUsedList whenever you want to use it.
Once you have the StorageFolder, you can then use GetFilesAsync() or GetFoldersAsync() method in your Parse instead of DirectoryInfo.GetDirectories or DirectoryInfo.GetFiles method.

Handle UnauthorizedAccessException When Directory.CreateDirectory() Run

I have a method that is helps to Create a Directory ifNotExist and Save the path of the File ,...
Now I have a little problem, There is an Exception casted when Directory.CreateDirectory(savePath); Runs. and I can't still get it right. I would like to know what I am doing wrong and how to fix it. Anyone Subjections is welcome. Thanks
Here is My Method:
protected void ASPxUpload_FileUploadComplete(object sender, DevExpress.Web.FileUploadCompleteEventArgs e)
{
if (e.IsValid)
{
String savepath = String.Format("{0}{1}\\", MapPath(#"~\TicketUploads\"), Session["lastcallid"]);
if (!Directory.Exists(savepath))
{
Directory.CreateDirectory(savepath);
}
String savefile = String.Format("{0}{1}", savepath, e.UploadedFile.FileName);
e.UploadedFile.SaveAs(savefile);
String urlPath = String.Format("{0}{1}\\{2}", #"~\TicketUploads\", Session["lastcallid"], e.UploadedFile.FileName);
fault_detail fltdet = session.GetObjectByKey<fault_detail>(Convert.ToInt32(Session["lastcallid"]));
fltdet.hasattachment = "Y";
fltdet.AttachUrl = urlPath;
fltdet.Save();
}
}
For more details of What I trying to do:
It simple allows the web server to identify the ID of the log user. and With that ID, We should therefore create a folder in Ticketuploads Folder. Which is like we are trying to create 2 folders at the same time. That is why I use: "{0}{1}\\"
please try this
string sessionVariable = Convert.ToString(Session["lastcallid"]);
string path = Path.Combine(MapPath(#"~\TicketUploads\"), sessionVariable);
if (!Directory.Exists(path))
{
Directory.CreateDirectory(path);
}
Also
I have Add Administration Permission to the Folder. As a Local user with IIS System. user Add Example: IIS_IUSRS(Username\IIS_IUSRS) That's it.

%AllUsersProfile%(%PROGRAMDATA%) gives a repetitive file path

I have an application written in C#, and I am seeking to write some information to the hidden ProgramData in order to access the same connection string from both the application's front end and back end.
I am accessing the directory using path variables as follows:
private bool ProgramDataWriteFile(string contentToWrite)
{
try
{
string strProgramDataPath = "%PROGRAMDATA%";
string directoryPath = Environment.ExpandEnvironmentVariables(strProgramDataPath) + "\\MyApp\\";
string path = Environment.ExpandEnvironmentVariables(strProgramDataPath)+"\\MyApp\\ConnectionInfo.txt";
if (Directory.Exists(directoryPath))
{
System.IO.StreamWriter file = new System.IO.StreamWriter(path);
file.Write(contentToWrite);
file.Close();
}
else
{
Directory.CreateDirectory(directoryPath);
System.IO.StreamWriter file = new System.IO.StreamWriter(path);
file.Write(contentToWrite);
file.Close();
}
return true;
}
catch (Exception e)
{
}
return false;
}
This seems to work correctly. However, my question is, when I used this path variable: %AllUsersProfile%(%PROGRAMDATA%)
instead, it expanded into an illegal(and redundant) file path : C:\ProgramData(C:\ProgramData)\
However, I thought that the latter path variable was the correct full name. Was I just using it incorrectly? I need to ensure that this connection info will be accessible to all users, will just using %PROGRAMDATA% allow that? I am using Windows 7 in case that is relevant.
From here:
FOLDERID_ProgramData / System.Environment.SpecialFolder.CommonApplicationData
The user would never want to browse here in Explorer, and settings changed here should affect every user on the machine. The default location is %systemdrive%\ProgramData, which is a hidden folder, on an installation of Windows Vista. You'll want to create your directory and set the ACLs you need at install time.
So, just use %PROGRAMDATA%, or better still:
Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData)

TreeView Where Root And All Nodes Thereafter Are Derived From First Sub-Folder - How To Specify Correct Path?

I am working on a simple, portable, single-form, application where the *.exe and a folder entitled UserGeneratedContent reside in the same directory. On my form I have a treeview that I want to populate with nodes corresponding to all sub-folders (if any exist) of UserGeneratedContent. The code I've pasted in below works almost the way I want it to, but it populates the treeview with UserGeneratedContent as the root node and in turn treats the sub-folders it finds as child nodes, etc.
string folder = #"UserGeneratedContent";
FolderHierachy.Nodes.Add(GetDirectoryNodes(folder));
private static TreeNode GetDirectoryNodes(string path)
{
var node = new TreeNode(Path.GetFileName(path));
var subDirs = Directory.GetDirectories(path).Select(d => GetDirectoryNodes(d)).ToArray();
node.Nodes.AddRange(subDirs);
return node;
}
At this stage I have tried just about every combination of #"UserGeneratedContent" I can think of - adding back-slashes etc, in an attempt to access the sub-folders but I'm having no luck. I know its probably something simple, but I'm stuck - what is the correct syntax to ensure that the method above looks into UserGeneratedContent to get the sub-folders?
Furthermore, I want the treeview control to allow the user to create, rename, and delete folders in any hierachy of their choice so I'm wondering what would be considered best practices in this regard?
Edit \ Update # 1 - 12.2.2012:
After a lot more trial and error I have given up on the code above - no matter what I tried I couldn't get it to work for some reason. Luckily the code below is working perfectly for me :-)
DirectoryInfo dirInfo = new DirectoryInfo(#"UserGeneratedContent");
DirectoryInfo[] subDirs = dirInfo.GetDirectories();
string pathToSubFolders = Path.Combine(#"UserGeneratedContent", subDirs[0].ToString());
PopulateTreeView(treeView1, pathToSubFolders);
private void PopulateTreeView(TreeView treeView, string path)
{
treeView.Nodes.Clear();
var rootDirectoryInfo = new DirectoryInfo(path);
treeView.Nodes.Add(CreateDirectoryNode(rootDirectoryInfo));
}
private static TreeNode CreateDirectoryNode(DirectoryInfo directoryInfo)
{
var directoryNode = new TreeNode(directoryInfo.Name);
foreach(var directory in directoryInfo.GetDirectories())
{
directoryNode.Nodes.Add(CreateDirectoryNode(directory));
}
return directory;
}
I need to add some error handling code to it to allow for there being no sub-folders under #"UserGeneratedContent" - as it is subDirs[0].ToString() throws an IndexOutOfRangeException if no sub-folders exist and I'm not exactly sure how to go about it so I'd be grateful for some pointers.
Edit \ Update # 2 - 12.2.2012:
For my error checking I've used a try-catch block as below:
try
{
string pathToSubFolders = Path.Combine(dirInfo.ToString(), subDirs[0].ToString());
PopulateTreeView(treeView1, pathToSubFolders);
}
catch (IndexOutOfRangeException)
{
//Do Something Here
}
The above code works, but can anyone tell me if I have gone about this the right way?
Thanks for reading.
if you haven't found an other solution yet, a simple way would be:
if(subDirs.Lenght != 0) // or > 0
{
string pathToSubFolders = Path.Combine(dirInfo.ToString(), subDirs[0].ToString());
PopulateTreeView(treeView1, pathToSubFolders);
}
else
{
//Do Something Here
}

DirectoryNotFoundException when calling Directory.GetDirectories on Environment.SpecialFolder.Favorites due to Domain Folder Redirection

I have some C# code that tries to get the Favorites for the currently logged in user. The code is part of a Taskbar Toolbar that gets loaded into the Windows Explorer process. I have a user who is using Windows Vista with UAC enabled on a domain that either has Roaming Profiles or Folder Redirection setup and enabled. When calling Directory.GetDirectories on the Favorites path, it throws "System.IO.DirectoryNotFoundException: Could not find a part of the path 'C:\Users\\Favorites\". Other users on other domains that do not have Roaming Profiles or Folder Redirection setup do not have this issue.
The user also reported that copying the path from the failed logs into the run prompt fails to load the path, but if they navigate to the path directly using explorer and then copy and paste that path into the run prompt, it works. He sent me both paths and they are exactly identical which doesn't make any sense at all.
My theory is that this is caused by the Folder Redirection where that path is actually pointing to a share on the server but the redirection is failing when trying to access the subdirectories (of the directoryInfo returned from Directory.GetDirectories). The initial directory works but all subdirectories of the initial directory fail to redirect correctly.
Has anyone come across a situation like this and/or know a workaround to gain proper access to redirected folders?
private void GetFavorites()
{
try
{
System.IO.DirectoryInfo dirInfo = new System.IO.DirectoryInfo(Environment.GetFolderPath(Environment.SpecialFolder.Favorites));
AddFavorites(dirInfo);
}
catch
{
}
}
private void AddFavorites(DirectoryInfo dirInfo)
{
foreach (System.IO.FileInfo fileInfo in dirInfo.GetFiles("*.url"))
{
//string alias = fileInfo.Name.Replace(".url", "");
if (!ItemsBookmarks.ContainsKey(fileInfo.Name))
ItemsBookmarks.Add(fileInfo.Name, fileInfo.Name);
}
foreach (System.IO.FileInfo fileInfo in dirInfo.GetFiles("*.lnk"))
{
if (!ItemsBookmarks.ContainsKey(fileInfo.Name))
ItemsBookmarks.Add(fileInfo.Name, fileInfo.Name);
}
foreach (System.IO.DirectoryInfo objDir in dirInfo.GetDirectories())
{
AddFavorites(objDir);
}
}
Thanks,
John
I believe the problem you are experiencing is related to Reparse Points.
See: http://msdn.microsoft.com/en-us/library/bb513869.aspx
See: What is the best way to check for reparse point in .net (c#)?
The problem can be avoided by using the following syntax:
private void AddFavorites(string dirPath)
{
try
{
foreach (string fileName in Directory.GetFiles(dirPath, "*.*", SearchOption.TopDirectoryOnly))
{
//string alias = fileInfo.Name.Replace(".url", "");
if (!ItemsBookmarks.ContainsKey(fileInfo.Name))
{
ItemsBookmarks.Add(fileName);
}
}
foreach (string subDirName in Directory.GetDirectories(dirPath, "*.*", SearchOption.TopDirectoryOnly))
{
AddFavorites(objDir);
}
}
catch
{
//error getting files or subdirs... permissions issue?
//throw
}
}

Categories

Resources