Manually I Have Mapped Network Drive Y:// To My System .Drive is having Manny Folders each Containg Single XMl File having Same as Folder .
Here I am Trying to Read Xml File From Network Location . But It is Giving Exception Directory Not Found . Below Code I am Using For that .
Fname = txtwbs.Text;
DirectoryInfo objDir = new DirectoryInfo("Y:\\");
\\Y:\\
protected void ImageButton1_Click(object sender, ImageClickEventArgs e)
{
_xmlpath = objDir + "\\" + Fname + "\\" + Fname + ".xml";
if (File.Exists(_xmlpath ))
{
reader(_xmlpath);
}
}
Here Fname is Folder Name Also Xml Name .Whatever User Will Enter the Name of File .
Grab this code: http://pastebin.com/RZnydz4Z
Then on the Application_Start of your global.asax put this:
protected void Application_Start(object sender, EventArgs e)
{
Utilities.Network.NetworkDrive nd = new Utilities.Network.NetworkDrive();
nd.MapNetworkDrive(#"\\server\path", "Z:", "myuser", "mypwd");
}
Then just use like a normal network drive, like this:
File.ReadAllText(#"Z:\myfile.txt");
You have this post tagged as both asp.net and asp-classic. From your code example, I'm guessing asp-classic doesn't apply.
If you are running in ASP.Net, the system wouldn't know about the mapped drive you've created. You should use the UNC path instead. If you aren't running the site with Windows Authentication, you'll also need to impersonate someone who has access to the share, as your anonymous user most likely will receive "Access Denied" errors.
Finally, I don't believe you need the DirectoryInfo call - use Path.Combine()
Ideally, you should use the UNC Path to access the files. \\server\share\path\to\file
Identity impersonate has done the trick for me
......
<system.web>
<identity impersonate="true" userName="yourdomain\yourusername"
password="yourpassword" />
......
......
Use this API. http://www.codeproject.com/Articles/6847/Map-Network-Drive-API
It the only way i have managed to do it in code.
Just modify the class, so it fits to you project.
Use a UNC path rather than a network drive and make sure the user running you application has permissions to access the folder and it's contents. "File not found" can mean wrong permissions or the path is just wrong.
Related
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)
I was able to open a directory on my computer locally but when I deployed my website to GoDaddy, I can't get it open. I am assuming it is some sort of security control. Here are the following actions I made:
set trust level to full in the web.config
set security to full control in my C:\ directory
Here is the following code to open a folder created in that directory:
protected void btnOpenFolder_Click(object sender, EventArgs e)
{
//Path to the customer's folder
string FolderPath = #"C:\" + customerId.ToString().PadLeft(4, '0') + " - " + lblName.Text;
if (System.IO.Directory.Exists(FolderPath))
{
//Opens the customer's folder
System.Diagnostics.Process.Start(FolderPath);
}
else
{
Response.Write("<script>alert('Must have the Dropbox directory in order to open the customer folder.');</script>");
}
}
Any suggestions would be great. Thanks in advance!
In our ASP.NET program a user can upload an image to a folder. The location of the image (including the name of the upload folder which is in the root directory) is stored as a variable called "path", ie. "Uploads/fileName.jpg".
To remove the image:
if (File.Exists("~/" + path))
{
File.Delete("~/" + path);
}
However, it fails to run because it can't verify that the file exists. Through some testing we noticed it's looking for "path" in the "system32" directory. Why would this be?
You need to use Server.Map path to ensure that the Tilde is resolved correctly.
MSDN Article is here -> http://msdn.microsoft.com/en-us/library/ms524632(v=vs.90).aspx
Your code would become
var fixedPath = Server.MapPath("~/" + path);
if (File.Exists(fixedPath))
{
File.Delete(fixedPath);
}
The File class is not aware of the IIS directory mapping, so it won't understand ~ correctly. You have to first use a method to map the app relative path to a local path with Server.MapPath
I was trying to write a code so that I could log the error messages. I am trying to name the file with the date and would like to create a new log file for each day. After going through a little look around, I came with the following code...
class ErrorLog
{
public void WriteErrorToFile(string error)
{
//http://msdn.microsoft.com/en-us/library/aa326721.aspx refer for more info
string fileName = DateTime.Now.ToString("dd-MM-yy", DateTimeFormatInfo.InvariantInfo);
//# symbol helps to ignore that escape sequence thing
string filePath = #"c:\users\MyName\mydocuments\visual studio 2012\projects\training\" +
#"discussionboard\ErrorLog\" + fileName + ".txt";
if (File.Exists(filePath))
{
// File.SetAttributes(filePath, FileAttributes.Normal);
File.WriteAllText(filePath, error);
}
else
{
Directory.CreateDirectory(filePath);
// File.SetAttributes(filePath, FileAttributes.Normal)
//Throws unauthorized access exception
RemoveReadOnlyAccess(filePath);
File.WriteAllText(filePath, error);
}
}
public static void RemoveReadOnlyAccess(string pathToFile)
{
FileInfo myFileInfo = new FileInfo(pathToFile);
myFileInfo.IsReadOnly = false;
myFileInfo.Refresh();
}
/*Exception thrown:
* UnAuthorizedAccessException was unhandled.
* Access to the path 'c:\users\anish\mydocuments\visual studio 2012\
* projects\training\discussionboard\ErrorLog\04\12\2013.txt' is denied.
*/
}
I found a forum that has discussed about a similar problem but using
File.SetAttrributes(filePath, FileAttributes.Normal) did not help neither did the RemoveReadOnlyAccess (included in the code above). When I check the properties of the folder, it has read only marked but even when I tick that off it comes back again. I checked the permissions on the folder and except for the special permission, which I was not able to change, everything is allowed.
Any suggestion on how I should proceed would be appreciated.
Why is access to the path denied? the link discusses about a similar problem, but I wasn't able to get my thing working with suggestions listed there.
Thanks for taking time to look at this.
Your path is strange : "My documents" directory must be "C:\Users\MyName\Documents\"
You can use Environment in order to correct it easily :
String myDocumentPath = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
Note that it will acces to "My documents" folder of the user that running your exe.
Second error, CreateDirectory must have a path in argument, not a file. using like you do will create a sub-directory with the file name. So you can't create a file with this name !
Try this :
String fileName = DateTime.Now.ToString("d", DateTimeFormatInfo.InvariantInfo);
String filePath = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments)
+ #"\visual studio 2012\projects\training\discussionboard\ErrorLog\";
String fileFullName = filePath + fileName + ".txt";
if (File.Exists(fileFullName ))
{
File.WriteAllText(fileFullName , error);
}
else
{
Directory.CreateDirectory(filePath);
[...]
}
}
Some possible reasons:
your app is not running under account which is allowed to access that path/file
the file is being locked for writing (or maybe reading too) by some other process
The first situation could be solved by checking under which account the process is running and verifying that the account has the appropriate rights.
The other situation can be solved by checking if any other process is locking the file (e.g. use tools like 'WhosLocking' or 'ProcessExplorer'
I had to run my app as an administrator in order to write to protected folders in c:. For example if debugging your app in visual studio make sure to right click on "C:\Program Files (x86)\Microsoft Visual Studio 12.0\Common7\IDE\devenv.exe" and choose "Run As Administrator". Then open your solution from there. My app was trying to write to the root of c:\
Check your antivirus, it might be blocking the file creation.
I have a website on Server A and it needs to find a directory on Server B.
On my aspx page, I have:
<mb:FileSystemDataSource
ID="fileSystemDataSource" runat="server"
RootPath="\\servername\Folder\Subfolder"
FoldersOnly="true" />
mb is assembly name alias.
On my aspx.cs page, I have:
protected void Page_Load(object sender, EventArgs e)
{
DataTable gridviewSource = DisplayFilesInGridView();
DataRow gridviewRow;
//sets the server path so it does not default to current server
string ServerPath = System.IO.Path.Combine(
"//",
this.fileSystemDataSource.RootPath);
//Get All Folders Or Directories and add in table
DirectoryInfo directory = new DirectoryInfo(Server.MapPath(ServerPath));
DirectoryInfo[] subDirectories = directory.GetDirectories();
}
Well, it throws an error on the Server.MapPath because it cannot find the server.
I am connected to the network.
I looked at IIS, and I am pretty sure that is not the problem. If so, I would really need specifics.
Any help would be appreciated.
string ServerPath = System.IO.Path.Combine(
"//",
this.fileSystemDataSource.RootPath);
Are you sure that "//" is what you're looking for? UNC paths start with "\\". Try running your program in debug mode and see what the actual ServerPath string turns out to be.
So Directory does not like Server.MapPath. I have to hard code the UNC string into the Directory constructor.