I have a folder named Template in my solution. I want some files to be copied in to it and accessed from it. How can i set the path to that? Will this folder be there when i deploy the application?
does this work?
File.Move(#"DebriefReportTemplate.docx", #"~\Template\DebriefReportTemplate.docx");
It won't be created unless you either build a setup/deployment project to create it at install time, or add code in your app to create it upon first invocation.
If you are worried about the existence of the Template folder, you could just create it at some point in your code.
string path = System.IO.Path.Combine("", "Template");
System.IO.Directory.CreateDirectory(path);
and then move the file
File.Move(#"DebriefReportTemplate.docx", #"Template\DebriefReportTemplate.docx");
EDIT: This answer is for an ASP.NET application.
If Template folder (including its content) is part of the web project, the deployment should work automatically. If you want to add files to this folder at runtime, you can use
Server.MapPath(#"~\Template\DebriefReportTemplate.docx")
, but be careful, the web application usually runs under an identity which has limited access to the local resources.
The same thing applies if you have a Win app. What you need to do is to add the folder and the files to the project, as Content. You will need a setup project though.
You may use
string sourceFile = Path.GetDirectoryName(Application.ExecutablePath)+#"\Template\DebriefReportTemplate.docx";
string destinationFile = #"C:\DebriefReportTemplate.docx";
// To move a file or folder to a new location:
System.IO.File.Move(sourceFile, destinationFile);
References :
MSDN: Copy Files & Folders
C# Examples: Get Application Directory [C#]
Related
I have a very simple .NET console application in Visual Studio. I am trying to write some words into a text file.
using (StreamWriter file = File.AppendText("log1.txt"))
{
file.WriteLine("Hello from the text file");
}
If the file does not exist, the application creates it in the autogenerated folder bin/Debug.
Is there a way to create this file in the project's directory, where I have .csproj file?
And more important, in real-world applications, when you work with files, you keep them in bin/Debug? That's why .NET creates them there firstly?
Is there a way to create this file in the project's directory, where I have .csproj file?
Yes, but this can only be done while you are working on your project. Once you are done developing it and try to publish it you won't have access to the location where you have .csproj file, because after publishing you can install it on any PC and it wont have the project you are working on.
And more important, in real-world applications, when you work with files, you keep them in bin/Debug?
No, I assume by real-world applications in your context you mean a published project '.exe' that you can run on any PC. Windows provides you three Data folders that you should use when writing your program so that it works smoothly after publishing:
User Data
Roaming User Data
All User Data
You can acess the above folders in .NET application using the Environment.SpecialFolder:
Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData)
Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData)
Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData)
As per your given code, try this :
var fileName = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData),
"log1.txt");
using (StreamWriter file = File.AppendText(fileName))
{
file.WriteLine("Hello from the text file");
}
This way you will be able to publish your program and it will still work smoothly without hard-coding the path as you were doing previously.
That's why .NET creates them there firstly?
If you don't specify a complete path, and just the file name .NET looks into the working directory of the executable, which in this case is bin/Debug
Is there a way to create this file in the project's directory, where I have .csproj file?
Yes. As explained here (second answer) you can use the post-build event to write down the value of $(ProjectDir) in a text file (using command echo $(ProjectDir) > ..\..\projectdir.txt). This macro contains the directory of your .csproj. This command will create the file projectdir.txt with your project directory after a build process so you read this file contents in your code and use what is inside it to pass to File.AppendText as the base directory to create your file log1.txt.
And more important, in real-world applications, when you work with files, you keep them in bin/Debug? That's why .NET creates them there firstly?
That depends on what you want to do. In your case the code creates the file at bin/Debug because that is where your executable are being executed. When you omit the full path to File.AppendText and just pass "log1.txt" as argument, it will create the file in the same folder as the executable are at. If you want a different folder you should specify the folder here (e.g. File.AppendText("C:/log1.txt") will create the file at C:/.
You can create the text file in the root of your project and use copy always to have them in the same place as your executable. If this is just a readonly text file then it's OK because windows doesn't allow you to modify the files reside in Programs folder in OS drive.
If you want your code to modify these text file then you need to put them in appdata folder. In real world example I did this on many project. All the database work my winforms, WPF application need goes in AppData folder.
I am creating a desktop application in which user can add persons and their images. Currently, the images folder is in bin folder but when I publish the application and run on client pc then images folder gone missing.
OR
Can I add images in Project->Properties->Resources programmatically?
Currently when I tried to user this Images Folder in PMS Project then images added in the folder present in the bin folder. How I can add in this folder?
Currently, I tried to access this is
string path = System.IO.Directory.GetCurrentDirectory();
Bitmap imgImage = new Bitmap(pictureBox1.Image);
System.IO.File.Copy(ImageName, Path.Combine(appPath, CNIC + Path.GetFileName(ImageName)), true);
I also want to keep images folder in the installation folder.
But it goes in the bin folder. How I can achieve this?
If you plan to have a private folder where your app store some data then you should really use the standard specs. You should create a folder inside the Environment.ApplicationData defined in the SpecialFolder enum
You could have something like this in the startup code of your application
string commonFolder = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);
string appFolder = Path.Combine(commonFolder, "PMS");
string imgFolder = Path.Combine(appFolder, "PoliceImages");
Directory.CreateDirectory(imgFolder);
Now those strings variables should be stored inside some kind of global configuration static class where you can retrieve them in any part of your application
If you want the folder be created automatically, you can add the basic images that would go into that folder and mark their Build Action and Copy to Output Directory properties appropriately in their properties window. This will make sure the folder gets created and also images will be copied in published copy.
Alternatively, If there are no images from development time, you can create the folder in client's installed location, using System.IO classes. Like -
System.IO.Directory.CreateDirectory("ss")
However, I would like to mention that its not a good practice to allow users to add images into a sub folder in bin unless when it is going to be a part of application itself after adding. If it is a content or data, try to keep it out of the folder where application binaries are installed. Probably,
Use an appropriate database storage.
C:\Users\[USERNAME]\AppData\Roaming
var directory = Environment.GetFolderPath(Environment.SpecialFolder.AppData);
OR
var directory = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
Or simply D:\Temp\[ApplicationName]
I am new in mvc and c# and I can't solve following problem:
I am trying to create a folder named "Items" in solution folder.
I have tryed to use CreateDirectory method:
Directory.CreateDirectory("~/Images");
But it didn't work for me - folder wasn't created ..
Partly working solution was to create a folder by :
Directory.CreateDirectory(Server.MapPath("~/Images"));
"Items" folder was created, but it is not included in the solution:
How to create folder in solution directory so that it is included in project ?
(I needs to by done by code not by hand)
You need to understand what solution and csproj file is used for
In general, they're being designed and used for development with Visual Studio, and once the project is compiled, all these files will be ignored and excluded from the deployment package
Directory.CreateDirectory(Server.MapPath("~/Images"));
The code above simply create the directory if not existed yet in the deployment package at run-time, so you won't see it in your solution unless you run the project locally (either debug/release mode, it does not matter here). However, everything will run normally in hosted environment (ex: IIS).
For your information, here's the brief of what solution and csproj is
solution (.sln) file: contains information to manage one or many individual projects, contains build environments (for each project), start up mode (useful when you want to start multiple projects in one run), project dependencies and so on. Take a note that VS also read from suo file (solution user options) which is used to defined user-custom preferences (you should not include the .suo file in the version control, because it's custom settings)
csproj file: define the structures of project, what the namespace is, what is static folders, embedded resources, references, packages, etc.
Lastly, if you create the folder manually, VS will auto include that folder into deployment package AND csproj, but depends on the file type, you might need to change the Build Action and Copy To Output Directory in file properties.
Hope it helps.
A deployed web application on a web server doesn't have any notion of Visual Studio solution or projects. So the Directory.CreateDirectory(Server.MapPath("~/Images")) is the correct way to create a folder inside your web application at runtime but we cannot be talking about including it into a solution because this hardly makes sense in a pre-compiled web application. If you create the directory on your local development machine, you could always manually include the folder to the corresponding .csproj file, but at runtime this will not make any difference whatsoever.
The reason I wanted to create a folder (if didn't exist) was to make sure it exits before I try to store image in it.
After reading posts here and a few google searches I have concluded that the proper way to handle image upload would be
To create (In my case) folder "Images" by hand to be sure it exists
Then storing uploaded img in existing folder:
string path =Server.MapPath("~/Images/"+ UploadedImageName);
file.SaveAs(path);
I had a folder on my desktop with files in it. I copied that into the folder of my solution and in the solution explorer I referenced that folder into the solution. However, Im not able to open files in that folder with a relative path.
The relative path from the cs-file would be "../FolderIAdded/blabla" as seen in the solution explorer. But in the windows explorer, the path is differen of course:
Solutionfolder
- SolutionFolder.sln
- Solutionfolder.v11.suo
- SolutionFolder
-- bin
-- obj
-- Properties
-- TheFolderIAdded
-- App.config
-- Form1.cs
-- etc.
Here, it would be "FolderIAdded/blabla"
Where do I have to put that folder?
My goal: I want to be able to open files from that folder in my c#-code with a relative path.
You're assuming that your program runs in the directory where your source code is located. That's not the case. Depending on your configuration, your program will execute from a directory inside Solutionfolder\bin.
One possible solution is to copy the file(s) to the output directory when you build your project.
Another alternative is to embed the files into your application's assembly at compile time, although this precludes editing of them after deployment. To do that, set Build Action to 'Embedded Resource', then you can access them using the GetManifestResourceStream method of the Assembly class. The filename you need to give it will be derived from the path within the project structure, so in your example it would be "TheFolderIAdded.Filename.ext".
Yes, that's a dot, not a backslash.
Assuming the files are embedded in the same assembly the code that wants to read them is in, the code will look something like
var assembly = Assembly.GetExecutingAssembly();
using (var stream =
assembly.GetManifestResourceStream("TheFolderIAdded.Filename.ext"))
using (var reader = new StreamReader(stream)) {
string fileContents = reader.ReadToEnd();
}
I don't think it's a good idea to write relative path from .cs file. Better build the path base on where the application is executed:
One example, there are plenty other on the web: How can I get the application's path in a .NET console application?
(Your application is not running in the solution's root folder but where the .exe file is locatated. For example when you debug a desktop application, it runs typically from [solution folder]/bin/debug/ )
Then make sure the file you want to open property Copy to Output Directory is set to Copy Always or Copy if newer. (Right click on the file in your Solution Explorer and click on "Properties" to be sure to access it.)
I have a MVC application that downloads a file and then has to unzip it and use the data.
Where would the correct location be to store this file?
If I were using a windows Forms application I would store it in the bin and use the following to get the path. I'm trying to do the same for a web application?
String path = Application.StartupPath;
Create a folder in the root of your project and call it 'Temp' or something similar.
Store the downloaded files in it.
I think the best place would be to create a folder outside the root folder of the application so that this folder won't be accessible by website users.
To access this folder you have mainly two options:
create a virtual directory on the IIS level and access it.
Use AspEnableParentPaths, here is an example: http://msdn.microsoft.com/en-us/library/ms524697%28v=vs.90%29.aspx