In my solution, I have static file directory at project ApiCon and my code is need to get static file directory is in project BLL and the file path url is /image/myimg.png.
Now that file can show in front end completely. I need to delete my image in static file directory when I call Api in controller, But I can't get path to delete that file.
How to get static file directory?
if (File.Exists(path))
{
File.Delete(path);
}
P.S. I need not to use Directory.GetParent() for find directory in other project.
Static files, while they should be located in the application folder, can be placed in whatever folder you want.
They could be in:
application_root/files/
application_root/files/static/
application_root/superman/batman/robinhood/
On the plus side, you get to put them wherever you want, even in multiple location. On the down side, there is no default static file directory.
Which means you'll have to keep track of the directory itself. The best way to store such information is in the web.config file of your application.
1. Add the config key in the <appSettings> of your web.config file.
<add key="StaticFileDirectory" value="MyStaticFiles" />
2. Add a reference to System.Configuration in your project.
It's listed under Assemblies > Framework.
3. Retrieve the config value.
string foldername = ConfigurationManager.AppSettings["StaticFileDirectory"];
4. Convert it to an absolute path.
string absoluteFolderPath = System.IO.Path.Combine(HttpRuntime.AppDomainAppPath, foldername);
5. Use it as you want to.
string absoluteFilePath = System.IO.Path.Combine(absoluteFolderPath, filename);
if (File.Exists(absoluteFilePath))
{
File.Delete(absoluteFilePath);
}
You can solve this issue by this way.
This function will search all subdirectories inside the given folder path ex:"C:\Users\NBY81HC\Desktop\hello" to return the file you want.
foreach (string file_path in Directory.GetFiles(#"C:\Users\NBY81HC\Desktop\hello", "test.txt", SearchOption.AllDirectories))
{
Console.WriteLine(file_path);//Return C:\Users\NBY81HC\Desktop\hello\aa\a2\test.txt
File.Delete(file_path);
}
Related
We have set of Test projects under one solution in Visual Studio. I want to read a Json file which is copied to the output directory from a different project folder in runtime. It's a test project. I can get the current project directory. But not sure how to get the other assembly's directory.
Solution looks as below
Project1 -> Sample.json (this file is set to copy to output directory)
Project2
While running my test in Project2 I want to access the file in Project1 from the output directory.
I used to access files in the same project folder with code as mentioned. But not sure how to get for a different project file. Now with replace I am able to achieve it. But sure this is not the right way
var filePath = Path.Combine("Sample.json");
var fullPath = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), filePath).Replace("Project1", "Project2");
Not sure how to get from other project. I am sure I can't use GetExecutingAssembly(), but what is the alternative. Somehow I can access it using the above dirty way of replacing the assembly name.
To get the location of another assembly, you get use a type from that assembly to get to the right Assembly instance, and thus its location:
typeof(FromOtherAssembly).Assembly.Location
First, I suggest that you could find the dll path in the solution.
Second, you can filter the json file from the path.
The next is my working code.
Please install Microsoft.Build and Microsoft.Build.Framework nugetpackages first.
string path= string.Empty;
var solutionFile =SolutionFile.Parse(#"D:\test.sln");// Your solution place.
var projectsInSolution = solutionFile.ProjectsInOrder;
foreach (var project in projectsInSolution)
{
if(project.ProjectName=="TestDLL") //your dll name
{
path = project.AbsolutePath;
DirectoryInfo di = new DirectoryInfo(string.Format(#"{0}..\..\", path));
path = di.FullName;
foreach (var item in Directory.GetFiles(path,"*.json")) // filter the josn file in the correct path
{
if(item.StartsWith("Sample"))
{
Console.WriteLine(item);// you will get the correct json file path
}
}
}
}
You can use the below code to do it in a better way
//solutionpath will take you to the root directory which has the .sln file
string solutionpath = Path.Combine(Directory.GetParent(Directory.GetCurrentDirectory()).Parent.Parent.FullName);
string secondprojectname = #"SecondProjectName\bin";
string finalPath = Path.Combine(solutionpath, secondprojectname);
you can use CopyToOutputDirectory in MSBuild
Hello i have to finish school project after another student.
And in whole program he used absolute path to file, the problem is it only works at one computer. Cuz this path is unique.
Could anybody tell me how can i replace this path just with file name?
string content = File.ReadAllText(filePath);
this.DocumentXml = XDocument.Parse(content);
this.xmlInfo = XDocument.Parse(content);
var groups = this.DocumentXml.Root.Elements("group");
foreach (var group in groups)
{
checkedListBox1.Items.Add(group.Attribute("name").Value);
}
// Adding data from your DNSFile to dataGridView1
hostsDataSet.Clear();
hostsDataSet.ReadXml(filePath);
dataGridView1.DataSource = hostsDataSet;
dataGridView1.DataMember = "item";
In this case "filepath" is text file with absolute path with file that he used.
Can you help me?
This is whole path to the file, that i create with Application.LocalUserAppDataPath: C:\Users\praktykant1\AppData\Local\WindowsFormsApplication1\WindowsFormsApplication1\1.0.0.0\test.txt
Problem in my case is that i have to create file that i use in program in AppData/Local folder.So on every computer the path will be different. And this program must work on every computer. Im just beginner so i am green in this subject.
This is precisely what config files are for... differences between environments in which the same code might execute.
Presumably the problem is that filePath is hard-coded, yes? Something like this?:
var filePath = #"c:\some\path\to\a\file.xml";
Instead, make that a configuration value. First add an entry to the App.config (or Web.config if this is a web application) in the appSettings node:
<appSettings>
<add key="filePath" value="c:\some\path\to\a\file.xml" />
<!-- any other settings already in place... -->
</appSettings>
Then use ConfigurationManager to get that setting. (You may need to add a reference to the System.Configuration assembly in the project.) Something like this:
var filePath = ConfigurationManager.AppSettings["filePath"];
You might also perform some error checking to make sure there's a value there at all (make sure filePath doesn't end up as a null or empty string, that is), make sure the file exists, etc.
At this point you can change the value in the config file without having to re-compile the code. So any new environment can set the config setting and use the application.
To get the file name of a path, just do this.
For example if your path is "C:\hello.txt", it becomes "hello.txt"
string fileName = Path.GetFileName(filepath);
If you do not like your file name to have any extensions
string fileNameNoEx = Path.GetFileNameWithoutExtension(fileName);
That way it becomes "hello"
If you set the variable filepath to be just the filename - it would look for this file in the directory where the executable file was started from (by default). This is called the working directory and you can find how to change the working directory online.
If you want to avoid using a full (or relative) path and just use the filename - expect it to be in that working directory.
In case of ASP.net you can do this,
if(FileUploadControl.HasFile)
{
try
{
string filename = Path.GetFileName(FileUploadControl.FileName);
FileUploadControl.SaveAs(Server.MapPath("~/") + filename);
StatusLabel.Text = "Upload status: File uploaded!";
}
catch(Exception ex)
{
StatusLabel.Text = "Upload status: The file could not be uploaded. The following error occured: " + ex.Message;
}
}
I am pretty new in C# and I am finding some difficulties trying to retrieve a jpg file that is into a directory of my project.
I have the following situation:
I have a Solution that is named MySolution, inside this solution there are some projects including a project named PdfReport. Inside this project there is a folder named Shared and inside this folder there is an header.jpg file.
Now if I want to obtain the list of all files that are inside the Shared directory (that as explained is a directory inside my project) I can do something like this:
string[] filePaths = Directory.GetFiles(#"C:\Develop\EarlyWarning\public\Implementazione\Ver2\PdfReport\Shared\");
and this work fine but I don't want use absolute path but I'd rather use a relative path relative to the PdfReport project.
I am searching a solution to do that but, untill now, I can't found it. Can you help me to do that?
Provided your application's Executable Path is "C:\Develop\EarlyWarning\public\Implementazione\Ver2", you can access the PdfReport\Shared folder as
string exePath = System.IO.Path.GetDirectoryName(Application.ExecutablePath);
string sharedPath = Path.Combine(exePath, "PdfReport\\Shared\\");
string[] filePaths = Directory.GetFiles(sharedPath);
Try to get the current folder by using this
Server.MapPath(".");
In a non ASP.NET application but WinForms or Console or WPF application you should use
AppDomain.CurrentDomain.BaseDirectory
If you want root relative, you can do this (assuming C:\Develop\EarlyWarning is site root)
string[] filePaths = Directory.GetFiles(Server.MapPath("~/public/Implementazione/Ver2/PdfReport/Shared"));
Or if you want plain relative,
//assuming you're in the public folder
string[] filePathes = Directory.GetFiles(Server.MapPath("/Implementazione/Ver2/PdfReport/Shared"));
Root relative is usually best in my experience, in case you move the code around.
You can right click on your file header.jpg, choose Properties, and select for example the option Copy always on the property "Copy to Output Directory".
Then a method like this, in any class that belongs to project PdfReport:
public string[] ReadFiles()
{
return Directory.GetFiles("Shared");
}
will work well.
Alternatively, if you have files that never change at runtime and you want to have access to them inside the assembly you also can embed: http://support.microsoft.com/kb/319292/en-us
I've C# project and it has Resources folder. This folder has some of txt files. This files have various file names.
I'm taking file names from any source as string variable. For example I have fileName string variable and test.txt file in Resources folder:
string fileName = "test.txt";
When I want to access this file as like below, I can:
WpfApplication.Properties.test.txt;
But, When I want to access it by this code, I can't.
WpfApplication.Properties.fileName;
I want to use fileName string variable and access this text file.
What can I do to access it?
Thanks in advance.
Edit :
I change form of this question:
I've string variable assigned any text file name. For example; I have a.txt, b.txt, c.txt, d.txt, etc.. I'm taking this file name as string variable (fileName) via some loops. So, I took "c.txt" string. And, I can access this file by code in below:
textName = "c.txt";
fileName = "../../Resources\\" + textName;
However, when I build this project as Setup Project and install .exe file to any PC, there is no "Resources" folder in application's folder. So,
../../Resources\
is unavailable.
How can I access Resources folder from exe file's folder?
You need to add a Resource File to your project wich has the extension .resx/.aspx.resx. You will then be able to double click on this file and edit the required resources/resource strings. To do this right click on Project node in Solution Explorer > Add > New Item > Resource File. Let us assume you have added a file called ResourceStrings.resx to the Properties folder and added a resource string with key name MyResourceString, to access these strings you would do
string s = Properties.ResourceStrings.MyResourceString;
I hope this helps.
I would strongly recommend you taking a look at: http://msdn.microsoft.com/en-us/library/aa970494.aspx
If your text files have build action set as Resource you can locate them in code like:
(assuming the file name is fileName and its located in Resources folder)
Uri uri = new Uri(string.Format("Resources/{0}", fileName), UriKind.Relative);
System.Windows.Resources.StreamResourceInfo info = Application.GetResourceStream(uri);
Then you can access info.Stream to get access to your file.
There is a text file that I have created in my project root folder. Now, I am trying to use Process.Start() method to externally launch that text file.
The problem I have got here is that the file path is incorrect and Process.Start() can't find this text file. My code is as follows:
Process.Start("Textfile.txt");
So how should I correctly reference to that text file? Can I use the relative path instead of the absolute path? Thanks.
Edit:
If I change above code to this, would it work?
string path = Assembly.GetExecutingAssembly().Location;
Process.Start(path + "/ReadMe.txt");
Windows needs to know where to find the file, so you need somehow specify that:
Either using absolute path:
Process.Start("C:\\1.txt");
Or set current directory:
Environment.CurrentDirectory = "C:\\";
Process.Start("1.txt");
Normally CurrentDirectory is set to the location of the executable.
[Edit]
If the file is in the same directory where executable is you can use the code like this:
var directory = Path.GetDirectoryName(Assembly.GetEntryAssembly().Location);
var file = Path.Combine(directory, "1.txt");
Process.Start(file);
The way you are doing this is fine. This will find the text file that is in the same directory as your exe and it will open it with the default application (probably notepad.exe). Here are more examples of how to do this:
http://www.dotnetperls.com/process-start
However, if you want to put a path in, you have to use the full path. You can build the full path while only caring about the relative path using the method listed in this post:
http://social.msdn.microsoft.com/Forums/en-US/vbgeneral/thread/e763ae8c-1284-43fe-9e55-4b36f8780f1c
It would look something like this:
string pathPrefix;
if(System.Diagnostics.Debugger.IsAttached())
{
pathPrefix = System.IO.Path.GetFullPath(Application.StartupPath + "\..\..\resources\");
}
else
{
pathPrefix = Application.StartupPath + "\resources\";
}
Process.Start(pathPrefix + "Textfile.txt");
This is for opening a file in a folder you add to your project called resources. If you want it in your project root, just drop off the resources folder in the above two strings and you will be good to go.
You'll need to know the current directory if you want to use a relative path.
System.Envrionment.CurrentDirectory
You could append that to your path with Path
System.IO.Path.Combine(System.Envrionment.CurrentDirectory, "Textfile.txt")
Try using Application.StartupPath path as default path may point to current directory.
This scenario has been explained on following links..
Environment.CurrentDirectory in C#.NET
http://start-coding.blogspot.com/2008/12/applicationstartuppath.html
On a windows box:
Start notepad with the file's location immediately following it. WIN
process.start("notepad C:\Full\Directory\To\File\FileName.txt");