Check if a file exists on the server - c#

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))

Related

Store locally a binary file file received as HTTP POST body [duplicate]

I want upload an image file to project's folder but I have an error in my catch:
Could not find a part of the path 'C:\project\uploads\logotipos\11111\'.
What am I do wrong? I want save that image uploaded by my client in that folder... that folder exists... ah if I put a breakpoint for folder_exists3 that shows me a true value!
My code is:
try
{
var fileName = dados.cod_cliente;
bool folder_exists = Directory.Exists(Server.MapPath("~/uploads"));
if(!folder_exists)
Directory.CreateDirectory(Server.MapPath("~/uploads"));
bool folder_exists2 = Directory.Exists(Server.MapPath("~/uploads/logo"));
if(!folder_exists2)
Directory.CreateDirectory(Server.MapPath("~/uploads/logo"));
bool folder_exists3 = Directory.Exists(Server.MapPath("~/uploads/logo/" + fileName));
if(!folder_exists3)
Directory.CreateDirectory(Server.MapPath("~/uploads/logo/"+fileName));
file.SaveAs(Server.MapPath("~/uploads/logo/" + fileName+"/"));
}
catch(Exception e)
{
}
Someone knows what I'm do wrong?
Thank you :)
Try this:
string targetFolder = HttpContext.Current.Server.MapPath("~/uploads/logo");
string targetPath = Path.Combine(targetFolder, yourFileName);
file.SaveAs(targetPath);
Your error is the following:
bool folder_exists3 = Directory.Exists(Server.MapPath("~/uploads/logo/" + fileName));
if(!folder_exists3)
Directory.CreateDirectory(Server.MapPath("~/uploads/logo/"+fileName));
You check if a directory exists, but you should check if the file exists:
File.Exists(....);
You need filename
file.SaveAs(Server.MapPath("~/uploads/logo/" + fileName+"/" + your_image_fillename));
Remove the last part of the path to save you have an extra "/"
It should be
file.SaveAs(Server.MapPath("~/uploads/logo/" + fileName);
Also you do not have a file extension set.

C# Why does System.IO.File.Exists keep coming up false?

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.

Check file exists or not using c#

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

File.Exists(file) is false but file exist

I'm add a file in one controller and in another controller I want check if the file is exist. I' using File.Exist(file), but it's always false, even if the file exist...
I adding file, and image is added successful.
if ((image!= null & image.ContentLength > 0))
{
string name = event.EventId.ToString() + ".jpg";
var fileName = name;
var path = Path.Combine(Server.MapPath("~/App_Data/Plakaty"), fileName);
plakat.SaveAs(path);
}
I'm checking in another controller if this file exist:
string file = "~/App_Data/Plakaty/" + wyd.EventId.ToString() + ".jpg";
ViewBag.file_exist = System.IO.File.Exists(file); //always is false
And my View: (It's returning only "No file")
#if (ViewBag.file_exist == true)
{
<p>File exist</p>
}
else
{
<p>No file</p>
}
You need to do the Server.MapPath again when checking the file and do the forward slash.
string file = Server.MapPath("~") + #"\App_Data\Plakaty\"
+ wyd.EventId.ToString() + ".jpg";
ViewBag.file_exist = System.IO.File.Exists(file ); //always is false
You forgot to write Server.MapPath when checking if file exist
Have you checked permissions?
The Exists method returns false if any error occurs while trying to determine if the specified file exists. This can occur in situations that raise exceptions such as passing a file name with invalid characters or too many characters, a failing or missing disk, or if the caller does not have permission to read the file. See documentation
However most likely is what #Obama answered about the path being wrong as you didn't call Server.MapPath

How to navigate a few folders up?

One option would be to do System.IO.Directory.GetParent() a few times. Is there a more graceful way of travelling a few folders up from where the executing assembly resides?
What I am trying to do is find a text file that resides one folder above the application folder. But the assembly itself is inside the bin, which is a few folders deep in the application folder.
Other simple way is to do this:
string path = #"C:\Folder1\Folder2\Folder3\Folder4";
string newPath = Path.GetFullPath(Path.Combine(path, #"..\..\"));
Note This goes two levels up. The result would be:
newPath = #"C:\Folder1\Folder2\";
Additional Note
Path.GetFullPath normalizes the final result based on what environment your code is running on windows/mac/mobile/...
if c:\folder1\folder2\folder3\bin is the path then the following code will return the path base folder of bin folder
//string directory=System.IO.Directory.GetParent(Environment.CurrentDirectory).ToString());
string directory=System.IO.Directory.GetParent(Environment.CurrentDirectory).ToString();
ie,c:\folder1\folder2\folder3
if you want folder2 path then you can get the directory by
string directory = System.IO.Directory.GetParent(System.IO.Directory.GetParent(Environment.CurrentDirectory).ToString()).ToString();
then you will get path as c:\folder1\folder2\
You can use ..\path to go one level up, ..\..\path to go two levels up from path.
You can use Path class too.
C# Path class
This is what worked best for me:
string parentOfStartupPath = Path.GetFullPath(Path.Combine(Application.StartupPath, #"../"));
Getting the 'right' path wasn't the problem, adding '../' obviously does that, but after that, the given string isn't usable, because it will just add the '../' at the end.
Surrounding it with Path.GetFullPath() will give you the absolute path, making it usable.
public static string AppRootDirectory()
{
string _BaseDirectory = AppDomain.CurrentDomain.BaseDirectory;
return Path.GetFullPath(Path.Combine(_BaseDirectory, #"..\..\"));
}
Maybe you could use a function if you want to declare the number of levels and put it into a function?
private String GetParents(Int32 noOfLevels, String currentpath)
{
String path = "";
for(int i=0; i< noOfLevels; i++)
{
path += #"..\";
}
path += currentpath;
return path;
}
And you could call it like this:
String path = this.GetParents(4, currentpath);
C#
string upTwoDir = Path.GetFullPath(Path.Combine(System.AppContext.BaseDirectory, #"..\..\"));
The following method searches a file beginning with the application startup path (*.exe folder). If the file is not found there, the parent folders are searched until either the file is found or the root folder has been reached. null is returned if the file was not found.
public static FileInfo FindApplicationFile(string fileName)
{
string startPath = Path.Combine(Application.StartupPath, fileName);
FileInfo file = new FileInfo(startPath);
while (!file.Exists) {
if (file.Directory.Parent == null) {
return null;
}
DirectoryInfo parentDir = file.Directory.Parent;
file = new FileInfo(Path.Combine(parentDir.FullName, file.Name));
}
return file;
}
Note: Application.StartupPath is usually used in WinForms applications, but it works in console applications as well; however, you will have to set a reference to the System.Windows.Forms assembly. You can replace Application.StartupPath by
Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location) if you prefer.
I use this strategy to find configuration and resource files. This allows me to share them for multiple applications or for Debug and Release versions of an application by placing them in a common parent folder.
Hiding a looped call to Directory.GetParent(path) inside an static method is the way to go.
Messing around with ".." and Path.Combine will ultimately lead to bugs related to the operation system or simply fail due to mix up between relative paths and absolute paths.
public static class PathUtils
{
public static string MoveUp(string path, int noOfLevels)
{
string parentPath = path.TrimEnd(new[] { '/', '\\' });
for (int i=0; i< noOfLevels; i++)
{
parentPath = Directory.GetParent(parentPath ).ToString();
}
return parentPath;
}
}
this may help
string parentOfStartupPath = Path.GetFullPath(Path.Combine(Application.StartupPath, #"../../")) + "Orders.xml";
if (File.Exists(parentOfStartupPath))
{
// file found
}
If you know the folder you want to navigate to, find the index of it then substring.
var ind = Directory.GetCurrentDirectory().ToString().IndexOf("Folderame");
string productFolder = Directory.GetCurrentDirectory().ToString().Substring(0, ind);
I have some virtual directories and I cannot use Directory methods. So, I made a simple split/join function for those interested. Not as safe though.
var splitResult = filePath.Split(new[] {'/', '\\'}, StringSplitOptions.RemoveEmptyEntries);
var newFilePath = Path.Combine(filePath.Take(splitResult.Length - 1).ToArray());
So, if you want to move 4 up, you just need to change the 1 to 4 and add some checks to avoid exceptions.
Path parsing via System.IO.Directory.GetParent is possible, but would require to run same function multiple times.
Slightly simpler approach is to threat path as a normal string, split it by path separator, take out what is not necessary and then recombine string back.
var upperDir = String.Join(Path.DirectorySeparatorChar, dir.Split(Path.DirectorySeparatorChar).SkipLast(2));
Of course you can replace 2 with amount of levels you need to jump up.
Notice also that this function call to Path.GetFullPath (other answers in here) will query whether path exists using file system. Using basic string operation does not require any file system operations.

Categories