Could not find a part of the path: Server.mapPath - c#

I'm trying to save a banner picture and before saving to a folder I'm checking and creating the respective folder as well but it gives me error even though I checked that the folder exists. Here is the code:
HttpPostedFileBase banner = Request.Files["banner"];
if (banner != null && banner.ContentLength > 0) {
var folder = Server.MapPath("~/images/Continents/");
if (!Directory.Exists(folder)) {
Directory.CreateDirectory(folder);
}
banner.SaveAs(Server.MapPath("~/images/Continents/" + image.FileName));
string x = "/images/Continents/" + image.FileName;
continent.BANNER = x;
}
Is there something I'm missing?

To concatenate Paths in Server.MapPath, use Path.Combine() as follow:
banner.SaveAs(Server.MapPath(Path.Combine("~/images/Continents", image.FileName)));

Related

Question about File Paths and opening those files C#

I have Three strings that are set to the current: year, month, day respectively using the "DateTimeNow". and I have set a path to a string of the root folder named "Custom_project" by grabbing the file path from a text file on the desktop.
They are named:
public string CurrentYear;
public string CurrentMonth;
public string CurrentDay;
public string CustomOrderFilePathTopFolder = File.ReadAllText("C:/desktop/Custom_project.txt");
//CustomOrderFilePathTopFolder now ='s C:/desktop/Custom_project/
Okay so I am trying to check to see if a folder exists(Folder Named: "CurrentYear" or in this case "2020" inside of the: "Custom_project" folder) and if not then create the folder with the string, if it does exist then it will then proceed to my next step which is essentially opening the file: "CurrentYear" or "2020, then repeating the same thing but inside of that folder: Custom_project/2020, for month and repeat one last time for day.
So In the end I would have a file path that looks like so: "C:/desktop/Custom_project/2020/07/12".
Now To My Question:
"HOW DO I GO ABOUT CHECKING IF A FILE NAMED "2020" EXISTS INSIDE OF THE CUSTOMPATHFOLDER AND IF IT DOESN'T THEN CREATE THAT FOLDER
I just tried using This(Which doesn't seem to work):
if (CustomOrderFilePathTopFolder == "")
{
MessageBox.Show("ERROR FILE PATH CANNOT BE EMPTY!");
}
else if (!Directory.Exists(CustomOrderFilePathTopFolder + CurrentYear))
{
Directory.CreateDirectory(CustomOrderFilePathTopFolder + CurrentYear);
}
This Does nothing for me so I tried this:
if (CustomOrderFilePathTopFolder == "")
{
MessageBox.Show("ERROR FILE PATH CANNOT BE EMPTY!");
}
else if (!Directory.Exists(CustomOrderFilePathTopFolder + "/" + CurrentYear))
{
Directory.CreateDirectory(CustomOrderFilePathTopFolder + "/" + CurrentYear);
}
Doesn't Work Either So I am At a loss Please Let me know how I would go about this please and thank you a ton!!
Try below steps
you need to first combine path to point proper file/folder
Check File exists or not
If not, then create folder with same name.
using System.IO;
...
var filePath = Path.Combine(CustomOrderFilePathTopFolder, CurrentYear))
if (!File.Exists(filePath))
{
Directory.CreateDirectory(filePath);
}

CreateDirectory creates Duplicate Directory in Public Folder

I have a Winforms application that is supposed to create a subdirectory in the Public Documents folder if the directory does not exist and save a text file to it. However, if the subdirectory does not exist, it actually creates another directory called Public Documents under "C:/Users/Public" rather than just creating a subdirectory under the existing "C:/Users/Public" folder. (In the example below the subdirectory is the variable 'token'.) So I end up with 2 folders called Public Documents:
Here is my code:
if (result == DialogResult.Yes)
{
subPath = #"C:\Users\Public\Public Documents\" + token + #"\Tests\";
}
else if (result == DialogResult.No)
{
subPath = #"C:\Users\Public\Public Documents" + #"\Tests\";
}
TestModel testCall = new TestModel
{
Name = frm.fileName,
MethodName = txtApiMethod.Text,
Parameter = rtxtJson.Text,
SchemaKey = txtSchemaKey.Text
};
bool exists = System.IO.Directory.Exists(subPath);
string fileName = frm.fileName + ".txt";
string json = JsonConvert.SerializeObject(testCall);
string filePath = subPath + fileName;
if (!exists)
{
System.IO.Directory.CreateDirectory(subPath);
}
using (StreamWriter file = File.CreateText(filePath))
{
file.Write(json);
}
Can someone tell me why it is creating a duplicate named directory, and what I can do to have just create a new subdirectory under the existing directory?
Any assistance is greatly appreciated!
C:\Users\Public\Public Documents is a display name. I have a french Windows, and the display name is C:\Users\Public\Documents publics
The real path is C:\Users\Public\Documents
Display :
Real :
To make sure you are using the correct folder path (for some reasons, d: could be used instead, or the path could be totaly different. Never use hardcoded path), you can use System.Environment.GetFolderPath(System.Environment.SpecialFolder.CommonDocuments); that links to C:\Users\Public\Documents, such as :
var PublicDocuments = System.Environment.GetFolderPath(System.Environment.SpecialFolder.CommonDocuments);
if (result == DialogResult.Yes)
{
subPath = PublicDocuments + #"\"+ token + #"\Tests\";
}
else if (result == DialogResult.No)
{
subPath = PublicDocuments + #"\Tests\";
}
See the documentation for more infos about System.Environment.SpecialFolder and System.Environment.GetFolderPath()

How can I fix this DirectoryNotFoundException?

I have a DirectoryNotFoundException on a .txt file if I use the full path it's working but I don't want to use the full path because I want the program work no matter where it is placed (compatibilty with the maximum of computer)
Here's my code
private void SaveClose_Click(object sender, RoutedEventArgs e)
{
if (Windowed.IsChecked == true)
windowed = true;
else
windowed = false;
string textWriteWindowed;
if (windowed == true)
{
textWriteWindowed = "-screen-fullscreen 0" + Environment.NewLine;
}
else
{
textWriteWindowed = "-screen-fullscreen 1" + Environment.NewLine;
}
var selectedResolution = ResolutionBox.SelectedItem.ToString();
var split = selectedResolution.Split('x');
widthChoose = Int32.Parse(split[0]);
heightChoose = Int32.Parse(split[1]);
string textWriteWidth;
textWriteWidth = "-screen-width " + widthChoose + Environment.NewLine;
string textWriteHeight;
textWriteHeight = "-screen-height " + heightChoose + Environment.NewLine;
File.WriteAllText(#"\Resources\arguments.txt", textWriteWindowed);
File.AppendAllText(#"\Resources\arguments.txt", textWriteWidth);
File.AppendAllText(#"\Resources\arguments.txt", textWriteHeight);
this.Close();
}
The first argument of File.WriteAllText takes a path as input. Whatever you have mentioned is not the absolute path but it is just the relative path of the file. WriteAllText creates the file but doesn't create the directory by itself. So something like:
File.WriteAllText(#"\arguments.txt", textWriteWindowed);
shall work (and create the file in the respective drive), but
File.WriteAllText(#"\Resources\arguments.txt", textWriteWindowed);
shall not work. Hence, if you want to create a file in the path where the application resides, you can do something like:
string folder=Path.GetDirectoryName(Process.GetCurrentProcess().MainModule.FileName);
File.WriteAllText(#"\arguments2.txt", "ABC");
If you want to create a directory, then you could do something like:
System.IO.FileInfo file = new System.IO.FileInfo(filePath);
file.Directory.Create();// If the directory already exists, this method does nothing.
System.IO.File.WriteAllText(file.FullName, textWriteWindowed);
Hope this answers your query.
you have to check whether the folder is exist before save the file,
if folder not exist create it using
Directory.CreateDirectory(...)
Directory.Exists(..)
you can use to check folder existence
IF you wanted to get the local path of the file you are executing use this:
var fInfo = new FileInfo(System.Reflection.Assembly.GetCallingAssembly().Location);
From there, you would do the following:
var parentDir = new DirectoryInfo(fInfo.DirectoryName);
var subDir = new DirectoryInfo(parentDir.FullName + "Resource");
if(!subDir.Exists)
subDir.Create();
This would ensure that you always have a folder in the directory of your executable. But just so you know, this is absolutely horrible code and should never ever be implemented in a production like environment. What if some knucklehead sysAdmin decides to place your program/folder in an area that the current user does not have access/writes too? The best place to write to is %APPDATA%, this will ensure the user always has read/write permissions to what you are trying to accomplish.
I don't know how but doing that worked for me :
File.WriteAllText(#"./arguments.txt", textWriteWindowed);
File.AppendAllText(#"./arguments.txt", textWriteWidth);
File.AppendAllText(#"./arguments.txt", textWriteHeight);

How to create a path using the Windows.Storage API?

System.IO.CreateDirectory() is not available on .NET for Windows Store Apps.
How can I implement this equivalent method? StorageFolder.CreateFolderAsync() creates a subfolder inside the current folder, but in my case I have a path like and need to create all folders that doesn't exist in this path.
The path is inside the app's sandbox in windows.
There's no API with exactly the same behaviour of System.IO.CreateDirectory(), so I implemented it using Windows.Storage classes:
// Any and all directories specified in path are created, unless they already exist or unless
// some part of path is invalid. If the directory already exists, this method does not create a
// new directory.
// The path parameter specifies a directory path, not a file path, and it must in
// the ApplicationData domain.
// Trailing spaces are removed from the end of the path parameter before creating the directory.
public static void CreateDirectory(string path)
{
path = path.Replace('/', '\\').TrimEnd('\\');
StorageFolder folder = null;
foreach(var f in new StorageFolder[] {
ApplicationData.Current.LocalFolder,
ApplicationData.Current.RoamingFolder,
ApplicationData.Current.TemporaryFolder } )
{
string p = ParsePath(path, f);
if (f != null)
{
path = p;
folder = f;
break;
}
}
if(path == null)
throw new NotSupportedException("This method implementation doesn't support " +
"parameters outside paths accessible by ApplicationData.");
string[] folderNames = path.Split('\\');
for (int i = 0; i < folderNames.Length; i++)
{
var task = folder.CreateFolderAsync(folderNames[i], CreationCollisionOption.OpenIfExists).AsTask();
task.Wait();
if (task.Exception != null)
throw task.Exception;
folder = task.Result;
}
}
private static string ParsePath(string path, StorageFolder folder)
{
if (path.Contains(folder.Path))
{
path = path.Substring(path.LastIndexOf(folder.Path) + folder.Path.Length + 1);
return path;
}
return null;
}
To create folders outside your app's sandbox in windows store app, you'll have to add the document library in app-manifest, along with file permissions.
For a much more detailed explanation regarding library and documents, Refer this blog

Check if path is in Program Files [duplicate]

This question already has answers here:
See if file path is inside a directory
(2 answers)
Closed 9 years ago.
How can I check in C# if the specific path is to directory in "Program Files" ?
C:\Program Files\someDir... -> is in Program Files
D:\Apps\someDir... -> isn't in Program Files
Thanks!
You can check a path in ProgramFiles(x86) by using the code below:
string path = "yourpath";
var programfileX86 = Environment.GetFolderPath(Environment.SpecialFolder.ProgramFilesX86);
if (path.IndexOf(programfileX86, StringComparison.OrdinalIgnoreCase) >= 0)
{
//Found path
}
There're some interseting and subtle issues with the problem:
You should compare paths case insenstive, e.g. "C:\PRogRAM FILES (x86)\Sample" is OK
Separators could be either / or \ so "C:/PRogRAM FILES (x86)/Sample" is OK as well
You should break on separatos only, e.g. "C:\Program Files (x86)MyData\Sample" is not OK
The Code:
public static Boolean PathIncludes(String path, String pathToInclude) {
if (String.IsNullOrEmpty(pathToInclude))
return false;
else if (String.IsNullOrEmpty(path))
return false;
String[] parts = Path.GetFullPath(path).Split(Path.AltDirectorySeparatorChar, Path.DirectorySeparatorChar, Path.VolumeSeparatorChar);
String[] partsToInclude = Path.GetFullPath(pathToInclude).Split(Path.AltDirectorySeparatorChar, Path.DirectorySeparatorChar, Path.VolumeSeparatorChar);
if (parts.Length < partsToInclude.Length)
return false;
for (int i = 0; i < partsToInclude.Length; ++i)
if (!String.Equals(parts[i], partsToInclude[i], StringComparison.OrdinalIgnoreCase))
return false;
return true;
}
public static Boolean InProgramFiles(String path) {
return PathIncludes(path, Environment.GetFolderPath(Environment.SpecialFolder.ProgramFilesX86)));
}
// Tests:
// Supposing that ProgramFilesX86 is "C:\Program Files (x86)"
InProgramFiles(#"C:\PRogRAM FILES (x86)\Sample"); // <- true
InProgramFiles(#"C:/PRogRAM FILES (x86)/Sample"); // <- true
InProgramFiles(#"D:/PRogRAM FILES (x86)/Sample"); // <- false
InProgramFiles(#"C:/PRogRAM FILES (x86)A/Sample"); // <- false
First you need to get the program files path. You can do that with System.Environment:
var programFilesPath = System.Environment.GetFolderPath(System.Environment.SpecialFolder.ProgramFiles);
If you want the 32 bit program files path you would just change the special folder you are looking for (System.Environment.SpecialFolder.ProgramFilesX86). Then I would do a contains:
var isInProgramFiles = myPath.ToLower().Contains(programFilesPath.ToLower());
That should get you 90% of the way there at least! Best of luck!
EDIT / Sanitize Note
As a side note - there are situations where you can have a valid input and this still wouldn't match. For example - using "/" instead of "\". If you want to make sure you handle these boundary cases correctly, you can create a "DirectoryInfo" object from your input string, validate that it is actually a folder and also standardize the formatting for it. That code looks something like:
if (!System.IO.Directory.Exists(inputPath)) return false;
var checkPath = (new System.IO.DirectoryInfo(inputPath)).FullName;
In this example "inputPath" is the same as "myPath" was above. That should do a moderately good job of sanitizing the input. Best of luck!
If you have a path variable:
string path = "/* whatever path */";
You can check if it is in a folder subfolder this way:
path.IndexOf('\\' + subfolder + '\\') != -1
Note that in more complex cases .. may revert you out of a subdirectory, meaning that you are not in folder f2 if you have something like this:
"\\base_on_drive\\subfolder\\f1\\f2\\..\\a_file.txt"
The .. will bump you back into it's parent folder f1.
if (path.Contains(Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles)) || (path.Contains(Environment.GetFolderPath(Environment.SpecialFolder.ProgramFilesX86)))
{
}
Assuming your program might be running inside of ProgramFiles, you will probably want to get the fullpath of any path you're checking (in case you get a relative path). In addition, C# has a handy SpecialFolder enumeration that you can use to get the ProgramFiles directory.
The following code will take in a path, convert it to a fullpath, and check if the ProgramFiles directory can be found inside of it. You may want to add some error handling (such as checking for null paths).
static string programfileX86 = Environment.GetFolderPath(Environment.SpecialFolder.ProgramFilesX86);
public bool IsInsideProgramFiles(string path)
{
// Get the fullpath in case 'path' is a relative path
string fullPath = System.IO.Path.GetFullPath(path);
return (fullPath.IndexOf(programfileX86, StringComparison.OrdinalIgnoreCase) >= 0);
}
Note: Depending on the systems your code is running in, you may want to check for both SpecialFolder.ProgramFiles and SpecialFolder.ProgramFilesx86.
Credit goes to Toan Nguyen's for the code to get the ProgramFiles directory:

Categories

Resources