I have an MVC project and a class library just for saving and deleting images.
I have the path to those images stored in a variable as a relative path
Content\images\ that I reference inside the Save() and Delete() methods.
The save method works as I would think but the delete throws an error as it's relating the current path from the window directory.
// Works fine
File.WriteAllBytes(Path.Combine(Settings.ImagesPath, filename), binaryData);
// Error saying it cannot find the path in the C:\windows\system32\folder
File.Delete(Path.Combine(Settings.ImagesPath, filename));
I'd like to be able to switch between relative and absolute paths in my Settings.ImagesPath string but every SO article I've tried works for one scenario or the other. What's the best way to convert absolute or relative paths to some common way to deal with them?
You should use Server.MapPath method to generate the path to the location and use that in your Path.Combine method.
var fullPath = Path.Combine(Server.MapPath(Settings.ImagesPath), filename);
System.IO.File.Delete(fullPath);
Server.MapPath method returns the physical file path that corresponds to the specified virtual path. In this case, Server.MapPath(Settings.ImagesPath) will return the physical file path to your Content\images\ which is inside your app root.
You should do the same when you save the file as well.
You can also check the existence of the file before attempting to delete it
var fullPath = Path.Combine(Server.MapPath(Settings.ImagesPath), filename);
if (System.IO.File.Exists(fullPath))
{
System.IO.File.Delete(fullPath);
}
Server.MapPath expects a relative path. So if you have an absolute value in the Settings.ImagePath, You can use the Path.IsPathRooted method to determine if it is a virtual path or not
var p = Path.Combine(Path.IsPathRooted(Settings.ImagesPath)
? path : Server.MapPath(Settings.ImagesPath), name);
if (System.IO.File.Exists(p))
{
System.IO.File.Delete(p);
}
When you use the virutal path, make sure it start with ~.
Settings.ImagesPath = #"~\Contents\Pictures";
Related
File.Copy(#"my program\\subfolder\\what i want to copy.txt", "C:\\Targetlocation");
How can i copy a text file from one folder to another using relative path.
To execute the File.Copy the source and destination will be a valid file path. in your case the destination is a folder not File. in this case you may get some exception like
Could not find a part of the path 'F:\New folder'
While executing the application, the current directory will be the bin folder. you need to specify the relative path from there. Let my program/subfolder be the folders in your solution, so the code for this will be like this:
string sourcePath = "../../my program/subfolder/what i want to copy.txt";
string destinationPath = #"C:\Targetlocation\copyFile.txt"
File.Copy(sourcePath, destinationPath );
Where ../ will help you to move one step back from the current directory. One more thing you have to care is the third optional parameter in the File.Copy method. By passing true for this parameter will help you to overwrite the contents of the existing file.Also make sure that the folder C:\Targetlocation is existing, as this will not create the folder for you.
File.Copy(#"subfolder\\what i want to copy.txt", "C:\\Targetlocation\\TargetFilePath.txt");
The sourceFileName and destFileName parameters can specify relative or
absolute path information. Relative path information is interpreted as
relative to the current working directory. This method does not
support wildcard characters in the parameters.
File.Copy on MSDN
Make sure your target directory exists. You can use Directory.CreateDirectory
Directory.CreateDirectory("C:\\Targetlocation");
With Directory.CreateDirectory(), you don't have to check if the directory exists. From documentation:
Any and all directories specified in path are created, unless they
already exist or unless some part of path is invalid. The path
parameter specifies a directory path, not a file path. If the
directory already exists, this method does nothing.
// Remove path from the file name.
string fName = f.Substring(sourceDir.Length + 1);
try
{
// Will not overwrite if the destination file already exists.
File.Copy(Path.Combine(sourceDir, fName), Path.Combine(backupDir, fName));
}
You can provide the relative path from your current working directory which can be checked via Environment.CurrentDirectoy.
For example if your current working directory is D:\App, your source file location is D:\App\Res\Source.txt and your target location is D:\App\Res\Test\target.txt then your code snippet will be -
File.Copy(Res\\Source.txt, Res\\Test\\target.txt);
How can I check if a file exists or not in the directory the executable is?
I know how I could code it like this.
string path = Application.StartupPath + "config.cfg"
if(!FileExists(path))
{
//create the file
}
But the problem I am facing is that, the file is created every single time, even when the file exists, overwriting the data of the cfg file with the default ones.
You are not creating the possible file path properly. Use Path.Combine like:
string path = Path.Combine(Application.StartupPath, "config.cfg");
You are getting a path without terminating \ from Application.StartupPath, later you are concatenating the file name to it, This will create an invalid path, and since that doesn't exist, you check fails.
Just to show, the actual reason for getting the error, you can fix your code like:
string path = Application.StartupPath +"\\"+ "config.cfg";
But, do not use the above code, instead use Path.Combine to join multiple path elements.
I'd like to save an uploaded file to a physical path by the method HttpPostedFileBase.SaveAs().
When I choose a physical path, an exception appears indicates that the path must be virtual.
var fileName = Path.GetFileName(fileurl.FileName);
var path = "C:/Projets" + fileName;
fileurl.SaveAs(Server.MapPath(path));
How can I change my code to be able to save the file every where I want?
The Server.MapPath works only with physical locations that are part of the website. If you want to save the file outside you could use the following:
var fileName = Path.GetFileName(fileurl.FileName);
fileurl.SaveAs(Path.Combine(#"c:\projects", fileName));
Make sure though that the account under which your application pool is executing is granted write permissions to this folder.
Server.MapPath is for virtual path. You can try to use Path.GetFullPath(path).
So I am reading a book about asp.net security. and one of the sections there was :
how to prevent directory traversal filename ( hacked filenames).
so the line of code was :
string fullPath = Server.MapPath(System.IO.Path.Combine(#"d:\inetpub\inbound\",filename));
but then I noticed the result of the combine which will be :
d:\inetpub\inbound\myfile.txt
But I remember that the parameter type should be virtual path and not filesystem path !
d:\inetpub\inbound\myfile.txt is not a virtual path!
what am I missing ?
p.s. this is the book : (wrox)
The code sample is wrong.
The role of Server.MapPath is indeed to transform a virtual path into a physical one. If you already have a physical path, there'a no need for Server.MapPath.
The code will probably throw an Exception with the message:
'd:\inetpub\inbound\myfile.txt' is a physical path, but a virtual path was expected.
You must use Server.MapPath to convert a virtual path (i.e., a path inside your website) to a physical path (such as D:\InetPub\...).
So you can do this:
var physicalPath = Server.MapPath("~/Incoming/Receivedfile.txt");
and then you can use physicalPath to actually access the file.
BTW the tilde in the filename above represents the root of the website the code is running under.
Relative paths in C# are acting screwy for me. In one case Im handling a set of Texture2d objects to my app, its taking the filename and using this to locate the files and load the textures into Image objects. I then load an image from a relative path stored in the class file and use a relative path that needs to be relative to Content/gfx. But if i dont load these textures these relative paths will fail. How can I garuantee that my rel path wont fail? In web work all rel paths are relative to the folder the file we're working from is in, can I set it up this way and make all rel paths to root folder where my app is located?
I recommend not using relative paths in the first place.
Use Path.Combine to turn your relative paths into absolute paths. For example, you can use this to get the full path to your startup EXE:
string exeFile = (new System.Uri(Assembly.GetEntryAssembly().CodeBase)).AbsolutePath;
Once you have that, you can get it's directory:
string exeDir = Path.GetDirectoryName(exeFile);
and turn your relative path to an absolute path:
string fullPath = Path.Combine(exeDir, "..\\..\\Images\\Texture.dds");
This will be much more reliable than trying to use relative paths.
If you are expecting a resource to be in the same directory as the executable file or in a sub directory of that directory, it's best to always use
string fullPath = System.IO.Path.Combine(System.IO.Directory.GetCurrentDirectory(), subPath);
or if you are worried that the working directory might be wrong you can do this:
string fullPath = System.IO.Path.Combine(System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetEntryAssembly().Location), subPath);
// [name space] is name space
//you should copy your file.-- into Depug file
string path = (Assembly.GetEntryAssembly().Location + "");
path = path.Replace("name space", "filename.--");
// [WindowsFormsApplication4] is name space
//you should copy your "mysound.wav" into Depug file
//example::
string path_sound = (Assembly.GetEntryAssembly().Location + "");
path_sound = path_sound.Replace("WindowsFormsApplication4.exe", "mysound.wav");
SoundPlayer player1 = new SoundPlayer(path_sound);
player1.Play();