I stored a file path in database table like this ../Document/5292013/cal.png. Now I want to check whether or not the file exists in the server folder. I am using the below code to check this, but it's not working for me.
if (File.Exists(Server.MapPath(root.GetElementsByTagName("FLD_DOC_ID")[0].InnerText)))
{
proof.HRef = Server.MapPath(root.GetElementsByTagName("FLD_DOC_ID")[0].InnerText);
}
Now I check using watch File.Exists(Server.MapPath("Document")) //Returns false, but server having the same folder.
Please help me to solve this.
You need to transform the file name to a virtual form before using MapPath. You must know the specifics of how it needs to be done. For example:
string fileName = root.GetElementsByTagName("FLD_DOC_ID")[0].InnerText;
fileName = fileName.Replace("..", "~");
if (File.Exists(Server.MapPath(fileName))
{
// you probably do not want MapPath here:
//proof.HRef = Server.MapPath(root.GetElementsByTagName("FLD_DOC_ID")[0].InnerText);
proof.HRef = System.Web.VirtualPathUtility.ToAbsolute(fileName);
}
Try to print out Server.MapPath(root.GetElementsByTagName("FLD_DOC_ID")[0].InnerText)
it might be pointing a wrong path or something
Any way, checking a file if it exists or not is very trivial:
if(File.Exists(the file path))
{
}
First you have to get filepath (filename) from database using select query then use that path with file.exists.
Example:
First get filename or filepath from database then,
if you get only filename then use below code:
if(File.Exits(Server.MapPath("Document/5292013/"+filename)))
{
}
or
if you get only filepath then use below code:
if(File.Exits(Server.MapPath("filename")))
{
}
Thanks
Related
I am not sure if I am in the right place to ask this, I am trying to create a table with all the PDF files that I have in a folder into my solution.
And I am trying to retrieve their names and put them in a table to access all of them throughout a link.
I got the following method, however, it not working.
protected void ListFiles()
{
const string MY_DIRECTORY = #"~/HistoricalFiles";
string strFile = null;
foreach (string s in Directory.GetFiles(Server.MapPath(MY_DIRECTORY), "*.*"))
{
strFile = s.Substring(s.LastIndexOf("\\") + 1);
//ListBox1.Items.Add(strFile);
}
}
Is there any way I can access all of them easily and display them in a good way?
By looking at your image, you should change the path of the folder. It is not in your root directory, it is inside Reports\API folder
const string MY_DIRECTORY = #"~/Reports/API/HistoricalFiles";
I am having a problem with coding my save-directory. I want it to create a folder called "Ausgabe" (Output) on the current users Desktop, but I do not know how to check if it already exists and if it doesn't then create it.
This is my current code for that part so far:
public partial class Form1 : Form
{
string path = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
// need some code here
}
What do I add in order to make it do what I want it to do?
You can check if a directory exists using
Directory.Exists(pathToDirectory)
and create a directory using
Directory.CreateDirectory(pathToDirectory)
EDIT In response to your comment:
string directoryPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop), "Ausgabe")
should give you the path to a folder named 'Ausgabe' in the users Desktop-folder.
Just use Directory.CreateDirectory. If the directory exists the method will not create it (in other words it contains a call to Directory.Exists internally)
public partial class Form1 : Form
{
string path = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
public Form1()
{
string myFolder = Path.Combine(path, "Ausgabe");
Directory.CreateDirectory(myFolder);
}
To use this method you need to add a using System.IO to the top of your Form1.cs file.
I wish also to say that the Desktop is not the most appropriate place to create a directory for your application. There is a proper place provided by the System and it is under the ProgramData enum (CommonApplicationData or ApplicationData)
string path = Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData);
As per this doc, the Directory.CreateDirectory Method (String) will
Creates all directories and subdirectories in the specified path
unless they already exist.
So it is fine to use like this:
string path = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
string desktopFolder = Path.Combine(path, "New Folder");
Directory.CreateDirectory(desktopFolder);
You can use the Directory.Exists() method: https://msdn.microsoft.com/en-us/library/system.io.directory.exists(v=vs.110).aspx
Your code would propebly look something like this:
public static void Main()
{
// Specify the directory you want to manipulate.
string path = #"c:\MyDir";
try
{
// Determine whether the directory exists.
if (Directory.Exists(path))
{
Console.WriteLine("That path exists already.");
return;
}
// Try to create the directory.
DirectoryInfo di = Directory.CreateDirectory(path);
Console.WriteLine("The directory was created successfully at {0}.", Directory.GetCreationTime(path));
// Delete the directory.
di.Delete();
Console.WriteLine("The directory was deleted successfully.");
}
catch (Exception e)
{
Console.WriteLine("The process failed: {0}", e.ToString());
}
finally {}
}
I have had a recent issue so here is my solution,
I had to find the deployed directory
var deployedDir = Assembly.GetEntryAssembly().CodeBase;
deployedDir = Path.GetDirectoryName(deployedDir);
deployedDir = deployedDir.Replace("file:\\", "");
var pathToDirectory= Path.Combine(deployedDir, "YourFileName");
Then do what the above answers show and create the directory if it doesnt exist,
Directory.CreateDirectory(pathToDirectory)
After going through all the related stuff to copying files i am unable to find an answer to my
problem of an exception occurring while i was trying to copy a file to an empty folder in WPF application. Here is the code snippet.
public static void Copy()
{
string _finalPath;
foreach (var name in files) // name is the filename extracted using GetFileName in a list of strings
{
_finalPath = filePath; //it is the destination folder path e.g,C:\Users\Neha\Pictures\11-03-2014
if(System.IO.Directory.Exists(_finalPath))
{
_finalPath = System.IO.Path.Combine(_finalPath,name);
System.IO.File.Copy(name, _finalPath , true);
}
}
}
While debugging exception is occuring at file.copy() statement which says
"FileNotFoundException was unhandled" could not find file
i already know about the combining path and other aspects of copy but i dont know why this exception is being raised.
I am a noob to WPF please help.........
Use following code:
public static void Copy()
{
string _finalPath;
var files = System.IO.Directory.GetFiles(#"C:\"); // Here replace C:\ with your directory path.
foreach (var file in files)
{
var filename = file.Substring(file.LastIndexOf("\\") + 1); // Get the filename from absolute path
_finalPath = filePath; //it is the destination folder path e.g,C:\Users\Neha\Pictures\11-03-2014
if (System.IO.Directory.Exists(_finalPath))
{
_finalPath = System.IO.Path.Combine(_finalPath, filename);
System.IO.File.Copy(file, _finalPath, true);
}
}
}
The GetFileName ()
only returns the actual name of the file (drops the path) what you want is a full path to the file. So you getting an exception because the 'name' does not exist on your drive (path is unknown)
You're variable, name, is most likely just the file name (i.e. something.jpg). When you use the File.Copy(...) method, if you do not supply an absolute path the method assumes a path relative to the executable.
Basically, if you are running your app in, for example, C:\Projects\SomeProject\bin\Debug\SomeProject.exe, then it is assuming your file is C:\Projects\SomeProject\bin\Debug\something.jpg.
string profile = "\\" + txtProfileLoad.Text + ".txt";
profile = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) + profile;
The variable profile is receiving the correct file path, but when I run it the File.Exists comes up false every time.
if (System.IO.File.Exists(profile) == true)
{
System.IO.StreamReader profileReader;
profileReader = new System.IO.StreamReader(profile);
do
{
profileLevel = profileLevel + profileReader.ReadLine() + "\r\n";
} while (profileReader.Peek() != -1);
loadName(profileLevel);
wordBeingUsed.finalWord = loadedName;
Close();
}
else
{
MessageBox.Show("Invalid file name. Please try again.");
}
There aren't any permissions stopping it from seeing the file.
Any help with this would be appreciated. It's been driving me crazy.
Is this a pre-existing file that you are trying to read? Or is this a new file that you are hoping to create? What is the value inside txtProfileLoad.Text, issue most likely is within this property.
Run a sanity check:
var profile = "mytestfile.txt";
var myFile = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), profile);
File.WriteAllText(myFile, "Testing file write");
if (File.Exists(myFile))
{
// Access works.
}
else
{
//Didn't work
}
If above code works, then it is most likely that the name you create from txtProfileLoad.Text is different from actual file on the drive. On the other hand, if this is a file that doesn't exist yet; then of course it would return false when you check Exists.
You can use a string variable and pass the file name to it:
string tempFile = txtProfileLoad.Text;
string profile = #"C:\temp\tempfile.txt";
Also check out if you could use the file open method instead of File.Exist.
As per MSDN:
true if the caller has the required permissions and path contains the name of an existing file; otherwise, false. This method also
returns false if path is Nothing, an invalid path, or a zero-length
string. If the caller does not have sufficient permissions to read the
specified file, no exception is thrown and the method returns false
regardless of the existence of path.
Have you tried running as an administrator? Try do "right click" on the Visual Studio icon and select "Run as Administrator", and see if you still encounter the same behaviour.
I am trying to check if a file is on the server with the C# code behind of my ASP.NET web page. I know the file does exist as I put it on the server in a piece of code before hand. Can anyone see why it is not finding the file. This is the code:
wordDocName = "~/specifications/" + Convert.ToInt32(ViewState["projectSelected"]) + ".doc";
ViewState["wordDocName"] = wordDocName;
if (File.Exists(wordDocName))
{
btnDownloadWordDoc.Visible = true;
}
else
{
btnDownloadWordDoc.Visible = false;
}
the file path should be physical not virtual. Use
if (File.Exists(Server.MapPath(wordDocName)))
File.Exists() and probably everything else you want to do with the file will need a real Path.
Your wordDocName is a relative URL.
Simply use
string fileName = Server.MapPath(wordDocName);
Use
Server.MapPath("~/specifications/" + Convert.ToInt32(ViewState["projectSelected"]) + ".doc")
to get the fully-qualified path. That should do the trick for ya.
You need to use Server.MapPath e.g.
wordDocName = Server.MapPath("~/specifications/" + Convert.ToInt32(ViewState["projectSelected"]) + ".doc");
ViewState["wordDocName"] = wordDocName;
if (File.Exists(wordDocName))
{
btnDownloadWordDoc.Visible = true;
}
else
{
btnDownloadWordDoc.Visible = false;
}
this might not work if the directory holding the file is referenced by a junction/symbolic link. I have this case in my own application and if I put the REAL path to the file, File.Exists() returns true. But if I use Server.MapPath but the folder is in fact a junction to the folder, it seems to fail. Anyone experienced the same behaviour?
The character "~" is a special char in ASP.NET to get virtual path specifications and simply means "root directory of the application". Is is not understood by the .NET BCL like the File API and must be mapped first into a physical path with Server.MapPath() as others stated.
You have to convert the path to a physical path with Server.MapPath(relativePath)
if (File.Exists(filePath))
wordDocName = "~/specifications/" + ViewState["projectSelected"] + ".doc";
btnDownloadWordDoc.Visible = File.Exists(Server.MapPath(wordDocName));
string docname="traintatkalantnoy.txt";
string a = (Server.MapPath(docname));
if (File.Exists(a))