File.Exists(file) is false but file exist - c#

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

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.

Not getting the Uploaded filepath in asp.net

I want to save file to a specific location with some folder creation based on my requirement. So I wrote the below code.
public string CreateFilePath(string addedFolderName)
{
string folderPath = ConfigurationManager.AppSettings["DocDirectory"].ToString();
string FileUplPath = folderPath + "\\" + addedFolderName + "\\";
if (!Directory.Exists(FileUplPath))
{
Directory.CreateDirectory(FileUplPath);
}
flUploadDocs.SaveAs(FileUplPath + Path.GetFileName(flUploadDocs.FileName));
return folderPath;
}
But I am unable to get the filepath here. I am getting it as null
getting null at
Path.GetFileName(flUploadDocs.FileName)
<asp:FileUpload ID="flUploadDocs" runat="server" />
Please suggest what is wrong here.
Path.GetFileName() returns the file name and extension of the specified path string
if im correct this only fills in the file name and not the directory + name.
Path.GetFileName(flUploadDocs.FileName)
possible solution
Path.GetFileName(FileUplPath+flUploadDocs.FileName)
eventough im confused why you try to retrieve the path again after just having saved it?
The issue is that the webservice does not have the fileupload data. Here is the full code from our extended conversation:
[WebMethod]
public static string InsertUpdateMWSiteData(MWInsertUpdateFields MWInsertUpdateFields)
{
string strInsertUpdateMWInfo = "";
try
{
Dashboard dshb = new Dashboard();
dshb.CreateFilePath(MWInsertUpdateFields.SapID + "_" + MWInsertUpdateFields.CandidateID);
strInsertUpdateMWInfo = CommonDB.InsertUpdateMWSiteInfo(MWInsertUpdateFields);
}
catch (Exception)
{
throw;
}
return strInsertUpdateMWInfo;
}
public string CreateFilePath(string addedFolderName)
{
string folderPath = ConfigurationManager.AppSettings["DocDirectory"].ToString();
string FileUplPath = folderPath + "\\" + addedFolderName + "\\";
if (!Directory.Exists(FileUplPath))
{
Directory.CreateDirectory(FileUplPath);
}
if (flUploadDoc.HasFile == true)
{
string strFilename = Path.GetFileName(flUploadDoc.FileName);
flUploadDoc.SaveAs(FileUplPath + Path.GetFileName(flUploadDoc.PostedFile.FileName));
}
return folderPath;
}
The problem is that after uploading a file, a request is sent to a webmethod which is being hosted in another instance of the program. This Webmethod checks its own instance for the fileupload control and data, and doesn't find it because it is in a different instance. This is why your fileupload control is returning null even on a sanity check of .HasFile().
One solution is to pass the data to the Webservice. You could for example pass the data to your webmethod as a byte[], and then on the webservice side reconvert it back into its original file type. After completing this process, save the file to your local filesystem. To do this you may need to pass the extension type and file name.
You may also want to add some validation to limit the file types accepted to only the most common file types like images, .doc, .excel, and whatever you have the library to support the conversion of.
If you want to save files directly to your filesystem using the upload control, you can do so but you will have to exclude the webservice step.
Please also see the discussion in chat for details.

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.

Opening a txt file automatically using OnSelectedIndexChanged

What I am trying to do is to read in a file to a richTextBox automatically with the OnSelectedIndexChange method. There arent any errors, it just flat out doesnt work. Heres the code that I am working with
public void comboBox1_OnSelectedIndexChanged(object sender, EventArgs e)
{
string selectedPath = comboBox1.SelectedItem.ToString();
if (File.Exists(#"C:\\Mavro\\MavBridge\\" + selectedPath + "\\ " + "Comment" + ".txt"))
{
try
{
Thread.Sleep(0500);
System.IO.StreamReader textFile = new System.IO.StreamReader(#"C:\\Mavro\\MavBridge\\" + selectedPath + "\\ " + "Comment" + ".txt");
richTextBox1.Text = textFile.ReadToEnd();
textFile.Close();
}
catch
{
MessageBox.Show("Error: File cannot be opened!", "Error");
}
}
else
{
MessageBox.Show("No comment was found in this folder", "Alert");
}
}
Just for fun, lets have you try something. First, replace the following line:
if (File.Exists(#"C:\\Mavro\\MavBridge\\" + selectedPath + "\\ " + "Comment" + ".txt"))
with this:
if(File.Exists(string.Format("C:\\Mavro\\MavBridge\\{0}\\Comment.txt", selectedPath)))
It looks like you had an extra space ("\\ " + "Comment"), so I'm sure that's why it never hits this block of code. Also, anytime you have an object that needs to be closed/disposed, more often than not it implements IDisposable, meaning you should encapsulate the object within a using block:
Thread.Sleep(0500);
try
{
using(System.IO.StreamReader textFile = new System.IO.StreamReader(string.Format("C:\\Mavro\\MavBridge\\{0}\\Comment.txt", selectedPath)))
{
richTextBox1.Text = textFile.ReadToEnd();
}
}
catch
{
MessageBox.Show("Error: File cannot be opened!", "Error");
}
However, this can be simplified even further by bypassing the StreamReader entirely and using System.IO.File.ReadAllText instead:
richTextBox1.Text = System.IO.File.ReadAllText(string.Format("C:\\Mavro\\MavBridge\\{0}\\Comment.txt", selectedPath));
Well, one problem comes from the fact that you have:
#"C:\\Mavro\\MavBridge\\" + selectedPath + "\\ " + "Comment" + ".txt"
Since you are using a verbatim string (the # at the beginning), you do not need to put double slashes.
For the rest, make sure your file exists.
Later edit: also I am not sure if you copy/pasted in a rush or something like that, but did you actually put the catch block inside the try ?
1) What is the error you see?
2) Are you positive the file exists?
3) Are you positive the path created by your code is the path you are expecting?
4) Why are you sleeping the thread?
5) Why not just use File.ReadAllText?
6) File.Exists will return false if the code is running with permissions that do not have access to a file, even if the file does exist. Does the user your code is running as, have permissions?
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 null, 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.
and
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.
Get rid of # before each string. Your directory as it currently is uses actual double slashes instead of C:\Mavro\MavBridge. Use single slashes with \ or go with # at the beginning, but don't use both.
Also, I would strongly suggest using Path.Combine instead of concatenating pieces together like that.

Check if a file exists on the server

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

Categories