Accessing Folders within the same server through ASP.NET - c#

Greeting.
I'm developing a ASP.NET Web Application and is trying to list the files in multiple layer of folders on the same server, but is on different folder (The files folder and Web Application folder).
The reason why I would like to access to the file is because I would required to read the creation date and the file name of the file. My application populate the details on gridview dynamically without any use of database and also provide the functions for downloading it one-by-one or zip all files together and download it as a compressed zip file.
Currently my approach is to share that folders out and my application is accessing it as if like a file system. To make it worse, I'm not allowed to host another IIS Web App.
Question:-
Is there any other workaround other than accessing it as a shared folder?
Updated
private List<FileData> getFilesList(DateTime? startDate, DateTime? endDate, string exDir)
{
DirectoryInfo dir = new DirectoryInfo(exDir);
List<FileData> fileDataList = new List<FileData>();
FileData fileEnt = null;
if (!dir.Exists)
{
return null;
}
if (startDate == null && endDate == null)
{
foreach (FileInfo fileInfo in dir.GetFiles())
{
fileEnt = new FileData();
fileEnt.fileName = fileInfo.Name;
fileEnt.createdDate = fileInfo.CreationTime;
fileEnt.stationCode = fileInfo.Name.Substring(0, 4);
fileEnt.filePath = fileInfo.DirectoryName;
fileDataList.Add(fileEnt);
}
}
else
{
foreach (FileInfo fileInfo in dir.GetFiles())
{
if (fileInfo.CreationTime > startDate && fileInfo.CreationTime < endDate)
{
fileEnt = new FileData();
fileEnt.fileName = fileInfo.Name;
fileEnt.createdDate = fileInfo.CreationTime;
fileEnt.stationCode = fileInfo.Name.Substring(0, 4);
fileEnt.filePath = fileInfo.DirectoryName;
fileDataList.Add(fileEnt);
}
}
}
return fileDataList;
}
This is a snippet of partially what is from my ASP.NET Web Application.
I'm trying to access it as in C:\FolderA\SubfolderB as I have created a page of configuration ASP.NET page to mimic folder browsing modal to allowed my user to specify which folder should my web application to list out all the files inside.
The flow goes like :-
1) User select a parent folder (Folder A)
2) System get list of subfolders from Folder A.
3) System iterate through all the subfolders to list all the subfolder's file name and information from the list of subfolders.
However, whenever I specify "F:\Reports\FolderA\" I'm unable to get the full listing. However, when I use \ServerName\FolderA, I can get the full list.
My application is located in E:\NETPrograms while my files are located in F:\Reports\FolderA.
Now, security team says that sharing folder is prohibited and I'm required to find another workaround for it.
Please advice.

i suppose you have given it permission by Sharing that folder with Everyone.
If you don't want to share it publicly, you can go to Folder Property -> Security and give Read permissions to IIS_USER.
This way it can be accessed by IIS_USER and used in your application and will not shared publicly.

Related

Cannot read any files or directories outside of my application directory

This is really annoying problem and it's going to drive me mad. I like to read information such like files, directories ect. but my app cannot find anything OUTSIDE its folder it runs in.
I'm using Visual Studio 2015 and developing Windows Universal apps.
This routine under works very well if I change the directory inside the folder my app run like "Assets" and any other folder. But outside of my app folder result is zero, not even any errors :-(
Ok, Here is the simple code, What I Do Wrong?
private void GetThem_Click(object sender, RoutedEventArgs e)
{
string myDir = #"c:\mydir\";
string[] files;
files = Directory.GetFiles(myDir,"*.jpg");
foreach (string stuff in files)
{
RESULT.Text = RESULT.Text + stuff + " , ";
}
}
A quick search would have given you the answer : It is not possible to access the file system like a classic desktop app. The answer of #Rico Suter explain you what you can acces and how :
Directories which are declared in the manifest file (e.g. Documents, Pictures, Videos folder)
Directories and files which the user manually selected with the FileOpenPicker or FolderPicker
Files from the FutureAccessList or MostRecentlyUsedList
Files which are opened with a file extension association or via sharing
Once a file is picked by the user, you can add it to MostRecentlyUsedList or FutureAccessList to use it again later using this snippet (C#) from MSDN :
StorageFile file = await savePicker.PickSaveFileAsync();
if (file != null)
{
// Add to MRU with metadata (For example, a string that represents the date)
string mruToken = Windows.Storage.AccessCache.StorageApplicationPermissions.MostRecentlyUsedList.Add(file, "20120716");
// Add to FA without metadata
string faToken = Windows.Storage.AccessCache.StorageApplicationPermissions.FutureAccessList.Add(file);
}
Then store the retrieved token because you will need it to access the file using GetFileAsync(token)

Not allowed to load local resource from App_Data folder

I need to server a larger amount of Pdf's which require authorisation in order to be able to download.
I have read that it is advisable to place them in the App_Data folder.
I have created three folders in the App_Data folder:
> SetOne
> SetTwo
> SetThree
I need to pass these files to my view.
Controller
var files = Directory.EnumerateFiles(Server.MapPath("~/App_Data/SetOne"));
return View(files);
View
<ul>
#foreach (var fullPath in Model)
{
var fileName = Path.GetFileName(fullPath);
var downloadPath = #Path.GetDirectoryName(fullPath) + "\\" + #fileName;
<li>#fileName</li>
}
</ul>
Using the above code, I am able to list the contents of the SetOne folder in an unordered list, however when I attempt to view one of the Pdf's I see:
Not allowed to load local resource:
file:///B:/Development/MyProject/MyProject.Web/App_Data/SetOne/sampleOne.pdf
How can I allow the application to give access to these files?
edit
I've also tried creating a new folder called Pdfs and moving the documents to this, however I get the same error message when I view in chrome dev tools.
Do I need to implement a Http Handler for this task?
Your approach is OK for WinForms application but shouldn't work for Web. downloadPath should contain the Url but not the physical path on the file (like some.com/pdfs/1.pdf)
You could use Server.MapPath for this case

C# - Access to Path is Denied, unable to access files

I'm working on a project that a series of images that are deposited in one area of memory (say from a memory stick or download), and distributes them out to their respective folders based on the name of the image - which should correspond with the names of the files in their respective folder.
I have the first few functions of the code written to make this happen and decided to test it by altering the code so that it would carry out the process on a collection of the files in the My Pictures folder.
What should have happened is that each file in the folder was copied to a folder in AppData called 'New Images', and added into the appropriate sub-directory or create the subdirectory if necessary.
This threw up an error stating that access to C:\Users\mark although it did not explain why or what to do about it.
I thought this might be a problem with accessing the My Pictures folder so I copied the images into a folder called 'Test Images' inside the AppData folder (so the program would now be just transferring files between two folders in AppData). The same error occurred and I don't really know what to do next, I have written and read from files in AppData many times before and never encountered this problem. I have also read various entries related to this on this forum but don't seem to be able to get a definitive answer in terms of what to do next!
The code that causes the exception can be seen below:
//main folder (Contains sub-folders for each patient)
string rootDirectory = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "\\New Images";
//variables for sub-directories cannot be given at this point as they are created using a part of the image name
string subDirectory;
//string subDirectory = Path.Combine(rootDirectory, imageName.Split('_')[0]);
string imageName;
//string imageName = Path.GetFileName(image)
string shortcutDirectory;
//string shortcutDirectory = My Documents + Subfolder name + file name
//list to hold all strings as bitmap image
List<Bitmap> images = new List<Bitmap>();
public void createDirectory()
{
//create filing construct for all files passed in from machines
//if main folder does not exist in AppData
if (!Directory.Exists(rootDirectory))
{
//create it
Directory.CreateDirectory(rootDirectory);
}
}
public void saveLatestImages()
{
//specific path for My Pictures only
string testImagesPath = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "\\Test Images";
//if there is a Pictures folder
if (Directory.Exists(testImagesPath))
{
//get number of files in folder
int fileCount = Directory.GetFiles(testImagesPath).Count();
//more than one file in folder
if (fileCount > 0)
{
//create data structures to store file info
//filePaths holds path of each file represented as a string
string[] filePaths = Directory.GetFiles(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "\\Test Images");
//for each file in Pictures...
for (int index = 0; index < fileCount; ++index)
{
//get name of image at current index
imageName = filePaths[index];
//separate the part relating to the patient name (everything before (DD/MM/YYYY))
string subSpecifier = imageName.Split('_')[0];
//add to root directory to form subfolder name
subDirectory = Path.Combine(rootDirectory, subSpecifier);
//subdirectory name formulated, check for pre-existing
//subfolder does not exist
if(!Directory.Exists(subDirectory))
{
//create it
Directory.CreateDirectory(subDirectory); //ERROR OCCURS
}
//otherwise, file will be added to existing directory
//take everything from end and folder\file division to get unique filename
string fileName = imageName.Split('\\').Last();
//add this to the existing subDirectory
fileName = Path.Combine(subDirectory, fileName);
//copy the image into the subfolder using this unique filename
File.Copy(imageName, fileName);
//add full filename to list of bitmap images
images.Add(new Bitmap(fileName));
//update the shortcut to the file in the image storage shortcut folder
shortcutDirectory = getShortcut(subSpecifier, fileName);
//delete image at original path (clear folder so images not copied on next load up)
//File.Delete(imageName);
}
}
}
}
Any help in where to look next would be greatly appreciated!
Thanks
Mark
Is this an ASP.net web application ? In that case can you try providing write permission to the IIS_IUSRS account.
The trick to solve this is ASP.net Impersonation .
Do not give full rights and run your app as an admin. Users will then have admin rights and I am sure you would want to avoid that.
For time being give full rights to everyone to your folder and try running your application as an administrator.
If that works then your can change permissions on your folder accordingly. Also make sure that your folder isn't readonly.

Getting directory from PageFiles folder of EPiServer

I'm having some thoughts about how the EPiServer PageFiles system work. When I get a global file it's simple to get the correct directory, I just write:
var dir = VirtualPathHandler.Instance.GetDirectory("~/Global/myfolder/", true)
But when I want to get files from the PageFiles folder it gets tricky for me. The path in the EPi backoffice upload says it is PageFiles/myfolder, but this doesn't return any folders
var dir = VirtualPathHandler.Instance.GetDirectory("~/PageFiles/myfolder/", true)
Now I see that files are saved different for each page, one page has the path /PageFiles/361/myfolder/ and another page has the path /PageFiles/65/myfolder/. All I want to do is be able to write
var dir = VirtualPathHandler.Instance.GetDirectory("~/PageFiles/myfolder/", true)
but to get any folder I have to write (for instance)
var dir = VirtualPathHandler.Instance.GetDirectory("~/PageFiles/65/myfolder/", true)
What is the correct way to get a PageFiles folder so I can access all files in it?
BTW, this is EPiServer 6.0
Try the GetPageDirectory method on your PageData object
http://sdk.episerver.com/library/cms6/html/M_EPiServer_Core_PageData_GetPageDirectory.htm

Find all files in a shared special folder (Virtual Folders)

Im looking for a way to find all files in an shared special folder (Virtual Folder).
The Desktop for example is an shared folder, there is a public Desktop for all users and a private Desktop. By navigating with the file explorer to Desktop you will see the contents of both desktops merged together.
Example:
Shared folder for all:
dir C:\Users\Public\Desktop
Testfile1
Testfile2
Folder for the current user:
dir C:\Users\usera\Desktop
Testfile3
Testfile4
Now I want to get all files from Testfile1 till Testfile4 by looping trough C:\Users\usera\Desktop
Someone has a clue howto get a list of the files of both directories merged together?
Also not only for Desktop, there are other folders that behave the same way.
Pseudocode:
arrayDesktop = FunctionThatGetsAllFilesFrom(#"C:\Usera\Desktop");
foreach (var file in arrayDesktop)
{
Console.WriteLine(file);
}
this should now print out
Testfile1
Testfile2
Testfile3
Testfile4
They are separate folders on the file system. Windows just combines them both to display on the desktop. You are going to have to get all the files from both folders and combine them into a single list.
You can get the list of files in a given folder with Directory.GetFiles.
Once you have the files from both folders, you can combine them with the Linq Concat extension method.
This isn't tested code so forgive any errors, but it should be enough to get you started.
foreach (string dir in Directory.GetDirectories(#"c:\Users"))
{
string fullDir = Path.Combine(dir, "Desktop");
if (Directory.Exists(fullDir))
{
foreach (string file in Directory.GetFiles(fullDir))
{
Console.WriteLine(file);
}
}
}
Unless you're running this as an administrator though, you're likely to run into security issues i.e. unable to read the directory. In this instance, you're going to need the System.Net.NetworkCredential object and store the admin account in local cache - something like this.
NetworkCredential credential = new NetworkCredential(username, password, domain);
CredentialCache credentialCache = new CredentialCache();
credentialCache.Add(new Uri(#"\\computer-uri"), "Basic", credential);
Use Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory) and Environment.GetFolderPath(Environment.SpecialFolder.CommonDesktopDirectory) to get the files on your Desktop and the Public one respectively.
For other Virtual Folders you can look at the documentation. But you still have to merge all the files yourself.

Categories

Resources