save and retrieve images from database by relative address in C# - c#

i have a windows form that contains two tabs . first tab is for save image and second is for retrieve.
Also my source pictures are in my bin project address like this :
C:\Users\BlackRose\Documents\Visual Studio 2012\Projects\RealState\RealState\bin\Debug\HomePics
now I wonder that how I can save address of pictures to sql server and retrieve them even I change my project location ...
I Already try these codes :
string path;
public myForm()
{
path = Environment.CurrentDirectory.ToString() + "\\HomePics";
openFileDialog1.InitialDirectory = path;
}
then write some sql and c# code in a function and save imagePath and imageName that no problem to save them.
but I'm sure I must configure path to set relative path, because the string of path that saved in db is like this :
C:\Users\BlackRose\Documents\Visual Studio 2012\Projects\RealState\RealState\bin\Debug\HomePics\pic1.jpg
with this method, the problem occurs when I want to move my project folder to otherwhere
and all of addresses in db will be useless.
could you tell me any useful method so i can retrieve it in any conditions?

You can use HomePics as folder name while saving the Path into Database as below:
path = "\\HomePics\\pic1.jpg";
while accessing Image Path from Database just Add Below Code:
String strRelativePath=getRelativePathfromDB();//gives you \Home\pic1.jpg
String strAbsoluteFilePath= System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().GetName().CodeBase).Replace("file:\\", "")+strRelativePath;
So finally strAbsoluteFilePath contains below Absolute Path:
C:\Users\BlackRose\Documents\Visual Studio 2012\Projects\RealState\RealState\bin\Debug\HomePics\pic1.jpg
the above path changes the dynamically depending on the location from where you are executing your project.
I hope this solves your problem :)

What you could do is:
Save the relative path in the database, i.e. path relative to \HomePics (root folder) in your example (provided that all files are in that folder and its subfolders).
In the config file of your application, add a setting to say where the root folder is located, e.g. in your <appSettings> you could have an entry <add key="ImagesRootFolder" value="C:\Images\HomePics" />. Alternatively, you could save the same information in the database as well, in a table separate to images.

Related

How to Get current date and create directory Everyday in C#?

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

C# Saving files on different PC's

The program I am writing is a stock inventory system.
So the PC I wrote the program on can locate the files and folders to update on the PC as necessary as the path is valid.
string path = "C:\\Users\\ThisPC\\Documents\\Stock Documents\\Reciepts";
if (!Directory.Exists("C:\\Users\\ThisPC\\Documents\\Stock Documents\\Reciepts"))
{
Directory.CreateDirectory(path);
}
var fileName = #"c:\Users\ThisPC\Documents\Stock Documents\Tyre_File.xml";
This line is also used when I am updating quantities when an order is taken.
So obviously when I run this program in visual studio on another PC this path isn't recognized.
Is there a way that I can add a pointer to create and store my folder and documents in the My Documents on any pc the program loads in?
UPDATE-------------------------------------------------------
string path = "C:\\Users\\ThisPC\\Documents\\Stock Documents\\Customer Reciepts";
if (!Directory.Exists("C:\\Users\\ThisPC\\Documents\\Stock Documents\\Customer Reciepts"))
{
Directory.CreateDirectory(path);
}
This is the only one it wont work for, it creates a folder within a folder when the form is loaded, but your method doesnt work for that?
I believe that
Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
is what you are looking for
You want the environment variable for MyDocuments, which will be unique for each user/computer.
String path = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);

asp file upload control, which one should be use?

ok, i found this on internet to upload some files.
if (FileUpload1.HasFile)
{
//create the path to save the file to
string fileName = Path.Combine(#"E:\Project\Folders", FileUpload1.FileName);
//save the file to our local path
FileUpload1.SaveAs(fileName);
}
and this
//check to make sure a file is selected
if (FileUpload1.HasFile)
{
//create the path to save the file to
string fileName = Path.Combine(Server.MapPath("~/Files"), FileUpload1.FileName);
//save the file to our local path
FileUpload1.SaveAs(fileName);
}
what is the difference, which one to use? i got confuse. by the way, if i can store file path in database, and next time when i want to delete or see that file, how can i retrieve that? so let say, first i add a record to database and uploaded a .doc file / excel file, next time when i want to edit that record, i want to retrieve the uploaded file, and show it in UI. thanks.
use second one cause it will convert relative or virtual path to real path itself . .u should get path from db and use it to resolve the path the same way you are storing and do manipulation on it delete and etc. for displaying url="~/Files/yourfilename"
yourfilefromdb -u retrieve it from db
string filepath = Path.Combine(Server.MapPath("~/Files"), yourfilefromdb);
File.Delete(filepath);
for showing
if it accessible directly u can just write url="~/Files/yourfilefromdb"
The only difference in two code blocks posted you is in specifying file path.
In case 1, static location is specified to save the file. It can cause problem, if location to save files differ in your production environment. It will require rebuild in that case.
While, in case 2, location is specified using relative path. So, it will always save files at "/Files" location.
//if you already know your folder is: E:\ABC\A then you do not need to use Server.MapPath, this last one is needed if you only have a relative virtual path like ~/ABC/A and you want to know the real path in the disk...
if (FileUpload1.HasFile)
{
string fileName = Path.Combine(#"E:\Project\Folders", FileUpload1.FileName);// they know the right path so .they using directly
FileUpload1.SaveAs(fileName);
}
if (FileUpload1.HasFile)
{
string fileName = Path.Combine(Server.MapPath("~/Files"), FileUpload1.FileName);// i don't know path is correct or not so they using Server.MapPath. . .
FileUpload1.SaveAs(fileName);
}

How to store image outside of the website's root directory

I want all images uploaded by users to be saved outside of my website directory.
Let me explain you all
Suppose i have a website deployed in a server and directory path is:
e.g. D:\TestWeb\
here currently some other directory i have added to store images as:
D:\TestWeb\imgProfile
D:\TestWeb\imgLocation
D:\TestWeb\Scan
but i don't want to store these inside of my root directory D:\TestWeb\
I want to store these into some other location as
E:\img\imgProfile
E:\img\imgLocation
E:\img\Scan
here i am not able to access this E:\img\imgProfile using http.
Please suggest any logic.
Set the path in the web.config file
<appSettings>
<add key="DocumentationLocation" value="E:\img\imgProfile" />
</appSettings>
In the code:
string savePath = ConfigurationSettings.AppSettings["DocumentationLocation"];
string filename = Path.GetFileName(FileUploadControl.FileName);
FileUploadControl.SaveAs(savePath + filename);
You can create a virtual directory in IIS, e.g. /Images that will point to D:\TestWeb\imgLocation. Then you just use MapPath to get the physical path to your image folder by using the virtual path /Images.

How can I add images into my .resx file?

By other than using AddResource button of Visual Studio, of course.
I submit a form, and an image file with it. In my controller action, I get the HttpPostedFileBase object, and its file name by using Path.GetFileName(). If I just use SaveAs() function to save the image file in my application, I cannot access it later for testing, because it gives me the "Not allowed to load local resource" error.
So I want to add the image to a .resx file and retrieve it later using ResourceManager or something. My question is, how can I add the image I have in the controller action into my .resx file?
I should also ask if this is the good approach for the purpose of adding and retrieving image files in my application.
EDITED:
Ok, using .resx to store images is not a good idea. My original problem was that I could save the image file, but when I tried to show it in my view, it gives "Not allowed to load local resource" error.
Here's the controller code:
public ActionResult UrunEkle(Urun urun, HttpPostedFileBase image)
{
Directory.CreateDirectory(Server.MapPath("~/App_Data/Images"));
var path = Path.Combine(Server.MapPath("~/App_Data/Images"), fileName);
image.SaveAs(path);
urun.ArtUrl = path;
// other stuff....
}
And in my view, I try to retrieve the image like this:
<img alt="#urun.name" src="#Url.Content(urun.ArtUrl)" />
But using Google Chrome, I get this "Not allowed to load local resource". How can I avoid this?
Forget trying to add the image to a RESX file; it's not designed to be modified at runtime.
Please post some code. The most likely thing is that the URL that you're serving up to use the image later is incorrect. Probably because you're returning the path of the file on the server, not a URL to the image within the context of the web site.
The error message from Chrome is telling you that it's trying to load a resource from the local file system on the client.
Url.Content converts a relative virtual path into an absolute virtual path and needs a URL starting with ~. You're currently passing in the absolute physical path to the image file and Url.Content is returning it, unchanged. You need the relative virtual path (~/App_Data/Images/Untitled.png) in urun.ArtUrl. This is the value that you passed in to Server.MapPath.

Categories

Resources