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
Related
get current date and make directory and second when directory is created, in that directory I have to store excel file and also save file as current date.
String Todaysdate = DateTime.Now.ToString("dd-MM-yyyy");
if (!Directory.Exists("C:\\Users\\Krupal\\Desktop\\" + Todaysdate))
{
Directory.CreateDirectory("C:\\Users\\Krupal\\Desktop\\" + Todaysdate);
}
This code have made directory with current date.
But when I want to store file in that directory, it generates the error:
Could not find a part of the path
'D:\WORK\RNSB\RNSB\bin\Debug\22-01-2020\22-01-2020.XLS
Belove path is store excel file that i have to store.
using (System.IO.StreamWriter file = new System.IO.StreamWriter(Todaysdate+"\\"+DateTime.Now.ToString("dd/MM/yyyy") +".XLS"))
Actually you are making the directory in a path then you are saving the .xls in another path.
You are making the directory using this path:
"C:\\Users\\Krupal\\Desktop\\" + Todaysdate
Then, here the path where you are trying to save the .xls:
Todaysdate+"\\"+DateTime.Now.ToString("dd/MM/yyyy") +".XLS"
The error shows the problem clearly, it could not fin this path:
D:\WORK\RNSB\RNSB\bin\Debug\22-01-2020\22-01-2020.XLS
While creating the .xls you are omitting the root path, so the process looks for the path 22-01-2020\22-01-2020.XLS in his working directory D:\WORK\RNSB\RNSB\bin\Debug.
You just need to align those paths: I sugget you to use relative paths, so here how you should fix your code:
String Todaysdate = DateTime.Now.ToString("dd-MM-yyyy");
if (!Directory.Exists(Todaysdate))
{
Directory.CreateDirectory(Todaysdate);
}
//then
using (System.IO.StreamWriter file = new System.IO.StreamWriter(Todaysdate+"\\"+DateTime.Now.ToString("dd/MM/yyyy") +".XLS"))
I presume you are running your WinForms application in Debug mode. This means that your current path is [your application path]\bin\Debug. If you look in file explorer, you will find that an executable has been created there. When using StreamWriter without an absolute file name, the file it tries to create is relative to the current execution path (in your case 'D:\WORK\RNSB\RNSB\bin\Debug'). StreamWriter will create a new file, if one does not exist, but it will not create a new folder, and you are passing it Todaysdate + "\\" which is effectively a new folder. Hence you are getting the error message.
To fix your problem, you need to provide the absolute path to your newly created directory thus:
using (System.IO.StreamWriter file = new System.IO.StreamWriter("C:\\Users\\Krupal\\Desktop\\" + Todaysdate+"\\"+DateTime.Now.ToString("dd/MM/yyyy") +".XLS"))
Winforms always expect directories inside Debug Folder, since it's EXE file is inside Debug and try to find it inside Debug folder.
In error it clearly shows that it is looking inside "Debug" folder.
Can you check whether File Exists in the mentioned folder created by you in C Drive.
// To Write File
System.IO.File.WriteAllLines(#"C:\Users\Public\TestFolder\WriteLines.txt", lines);
You can follow this MSDN Post, hope it helps, if Yes, please Upvote it
https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/file-system/how-to-write-to-a-text-file
I've created a file with the filepath of simply "test.txt" using File.Create method.
I've managed to email this file to myself using an email class and the filepath of "test.txt".
I want to find the actual file in my project folder, but can't see to find it even with a search for test.txt.
Is it a temp file, and where would it be saved to?
I'm creating the file with the following code:
public void createCSVFile()
{
string fileLocation = "test";
mFilePath = fileLocation+".txt";
if (!File.Exists(mFilePath))
File.Create(mFilePath).Close();
}
I think the following will help you with mapping your files in a specific location to help you further:
Server.MapPath specifies the relative or virtual path to map to a physical directory.
Server.MapPath("."), Server.MapPath(null), Server.MapPath("") will return the physical directory of the file being executed
Server.MapPath("..") will return the parent directory
Server.MapPath("~") will return the physical path to the root of the application
To give you an example if you have a website that is stored on disk at C:\Website the mapPath will return the following :
Server.MapPath("..") will return : "C:\Website"
Server.Mappath(".") will return "C:\Website{controllerName}"
Server.MapPath("~") will return : "C:\Website"
I already know how to browse for an image using open file dialog. So let's say we already got the path :
string imagePath = "Desktop/Images/SampleImage.jpg";
I want to copy that file, into my application folder :
string appFolderPath = "SampleApp/Images/";
How to copy the given image to the appFolderPath programmatically?
Thank you.
You could do something like this:
var path = Path.Combine(
System.AppDomain.CurrentDomain.BaseDirectory,
"Images",
fileName);
File.Copy(imagePath, path);
where fileName is the actual name of the file only (including the extension).
UPDATE: the Path.Combine method will cleanly combine strings into a well-formed path. For example, if one of the strings does have a backslash and the other doesn't it won't matter; they are combined appropriately.
The System.AppDomain.CurrentDomain.BaseDirectory, per MSDN, does the following:
Gets the base directory that the assembly resolver uses to probe for assemblies.
That's going to be the executable path you're running in; so the path in the end (and let's assume fileName is test.txt) would be:
{path_to_exe}\Images\test.txt
string path="Source imagepath";
File.Copy(System.AppDomain.CurrentDomain.BaseDirectory+"\\Images", path);
\ System.AppDomain.CurrentDomain.BaseDirectory is to provide path of the application folder
iam trying to fill dropdown box feteching folder name from server but this code showing error.its working in local .but not working in server.can any one help on this
DirectoryInfo dirInfo = new DirectoryInfo(Server.MapPath(#"~\\*.***.***.**\Flextronics\Common\Surendra"));
// DirectoryInfo dirInfo = new DirectoryInfo("D:\\New Folder");
ddlModel.DataSource = dirInfo.GetDirectories();
ddlModel.DataBind();
Server.MapPath(#"~\\*.***.***.**\Flex... return virtual path and it works for you on local because you have physical path "D:\...."
So you will have to use Request.MapPath("~/....."); because it Maps the specified virtual path to a physical path.
the ~ symbol looks to the parent folder of your code file on your local machine
To access a UNC on a network drive, you need something similar to:
Server.MapPath("\\\\servername\\folder\\desiredfile.ext");
The "\\\\" escapes the characters and you need to do that to navigate correctly.
Directory does not like Server.MapPath. Hard code it in:
...new DirectoryInfo("stringUNCtoLoadFilesFrom");
net/C# application I have list of items.
In the code behind:
I want to assign a picture from my local resources for each item. the items name and the picture names are the same.
The pictures are all in a "image" folder in my project.
Example of how I assign a picture to an item:
Item1.PictureUrl = "images/items/" + item1.Name + ".jpg";
I have items that don't have pictures. I want to assign for them a default picture.
I tried to check if the picture exists using this:
foreach(ObjectItem item in ListOfItems)
{
if(File.Exists("images/items/"+item.Name+".jpg"))
item.PictureUrl = "images/items/"+item.Name+".jpg";
else
item.PictureUrl= "images/Default.jpp";
}
But the File.Exists method is always returning false, even if the picture exist.
I also tried to use '\' instead of '/' but didn't work
How can I do it?
Thank you for any help
You need to convert the relative file path into a physical file path in order for File.Exists to work correctly.
You will want to use Server.MapPath to verify the existence of the file:
if(File.Exists(Server.MapPath("/images/items/"+item.Name+".jpg")))
Also, when you use Server.MapPath, you should usually specify the leading slash so that the request is relative to the web application's directory.
If you don't provide the leading slash, then the path will be generated relative to the current page that is being processed and if this page is in a subdirectory, you will not get to your images folder.
.Net Core Solution
1- Write this at the top of your View (Injecting IHostingEnvironment here);
#inject Microsoft.AspNetCore.Hosting.IHostingEnvironment hostingEnv
2- Write this to the place of image(Doing existence check);
var path = System.IO.Path.Combine(hostingEnv.WebRootPath, "MyFolder", "MyImage.jpg");
if (System.IO.File.Exists(path))
{
<img class="img-fluid" src="~/MyFolder/MyImage.jpg" alt="">
}
var path = $#"C:\Fotos\Funcionarios\1.Png";
FileInfo file = new FileInfo(path);
if (file.Exists.Equals(true))
{
//faz algo
}