Saving images to a project folder in asp.net/c# - c#

In my method, I'm trying to save an image in a folder in the directory of my project. I have tried just putting the direct filepath of the folder, but that gives me an error when the project runs.
Is there a built-in extension of some kind in c# that would allow me to save this image in a folder in my directory; or way to simply access my directory without drilling to where my project is saved on my computer?
private void CreateBarcode()
{
var bitmapImage = new Bitmap(500,300);
var g = Graphics.FromImage(bitmapImage);
g.Clear(Color.White);
UPCbarcode barcode = new UPCbarcode(UPCbarcode.RandomGeneratedNumber(), bitmapImage, g);
string filepath=#"images/image1.jpg";
bitmapImage.Save(filepath,System.Drawing.Imaging.ImageFormat.Jpeg);
}

You can always use the AppData folder,
string path = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData)

Assuming the "Image" folder is in the root directory of your Project use:
Server.MapPath("~/Image" + filename)
you can check if the file already exist at a location by :
if (!File.Exists(filePath))
{
// Your code to save the file
}

I can guess that there is similarity in the name of the image file
try putting it under a different name
like
string filepath = # "images / blabla or AI.jpg";

Use this
string filepath= Application.StartupPath + "\images\image1.jpg";
bitmapImage.Save(filepath,System.Drawing.Imaging.ImageFormat.Jpeg);

Related

Get image file path from resources

I have an image file day.jpg in Resources folder and I want to access it in the code as string path not as byte[] img
Here's what I have tried.
string dayWallpaper = Assembly.GetExecutingAssembly().Location + #"..\..\Resources\day.jpg";
// Didn't found it
string dayWallpaper = Resource.day;
// Outputs byte[] and gives me an error
Then I tried to convert the byte[] to String didn't work as well
static byte[] SliceMe(byte[]? source, int pos)
{
byte[]? destfoo = new byte[source.Length - pos];
Array.Copy(source, pos, destfoo, 0, destfoo.Length);
return destfoo;
}
static string ByteToPath(path)
{
String file = Encoding.Unicode.GetString(SliceMe(path, 24)).TrimEnd("\0".ToCharArray());
return file
}
Outputs black screen
Later I search for the file
if (File.Exists(dayWallpaper))
{
do stuff
}
else
{
Console.WriteLine("File does not exists");
}
And gives me the else statement.
In the answer you posted to your question, the fact that your relative path works is an "accident" that would fail on any other device deploying your app because without the existence of the source code project the path doesn't exist. One good option is to mark the day.jpg file as Copy to Output Directory at which point most installer bundlers will pick it up and deploy it in your setup.exe, msi etc. If you are specifically using the Visual Studio IDE, you would do it like this:
Now, at runtime, to acquire the path to the copied file:
var srce = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Resources", "day.jpg");
However, there is more work to be done, because you state that you "want to store the image in a folder in the executable and the user could add more images later on." The present location of the file is not suitable for that purpose, so I would recommend the additional step of creating an AppData entry for the user to store their created content.
// Obtain a folder that "the user could add to later on".
var appData =
Path.Combine(
Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData),
typeof(Program).Assembly.GetName().Name
);
Directory.CreateDirectory(appData);
Since you mention wanting to store the day.jpg image in that folder, go ahead and copy it to the AppData location (if not already there from a previous run of your app).
var dest = Path.Combine(appData, "day.jpg");
// Copy the image (if it's not there already) into folder that the user can add to.
if (!File.Exists(dest))
{
File.Copy(
sourceFileName: srce,
destFileName: dest
);
}
Alternatively, you could set the BuildAction to EmbeddedResource and manipulate the file as a byte stream and achieve the same end result.
I managed to do it this way
string resourcePath = Path.GetFullPath(Assembly.GetExecutingAssembly().Location + #"\..\..\..\..\Resources");
string dayWallpaper = resourcePath + #"\day.jpg";

Issue in File path

In my project there is a folder and in that folder there is text file. I want to read that text file
string FORM_Path = #"C:\Users\...\Desktop\FormData\Login.txt";
bool first = true;
string line;
try
{
using (StreamReader streamReader = File.OpenText(FORM_Path))
{
line = streamReader.ReadLine();
}
}
but I always get an error - file does not exist. how can i solve the problem in the path of text file.
Make sure your file's properties are set to copy the file to output directory. Then you can use the following line to get full path of your text file:
string FilePath = System.IO.Path.Combine(Application.StartupPath, "FormData\Login.txt");
You path is not in correct format. Use #".\FormData\Login.txt" instead of what you have
You are trying to give relative path instead of physical path. If you can use asp.net use Server.MapPath
string FORM_Path = Server.MapPath("~/FormData/Login.txt");
If the text file is in execution folder then you can use AppDomain.BaseDirectory
string FORM_Path = AppDomain.CurrentDomain.BaseDirectory + "FormData\\Login.txt";
If it is not possible to use some base path then you can give complete path.
Avoid using relative paths. Instead consider using the methods in the Path class.
Path.Combine
Path.GetDirectoryName
Step 1: get absolute path of the executable
var path = (new System.Uri(Assembly.GetEntryAssembly().CodeBase)).AbsolutePath;
Step 2: get the working dir
var dir = Path.GetDirectoryName(path);
Step 3: build the new path
var filePath = Path.Combine(dir , #"FormData\Login.txt");

C# mass File renamer

i want to create C# mass file renamer, here is my UI
i have created tes folder, inside of tes there's a file which is 1.txt.
i want to create my program to add prefix and suffix to the files, so 1.txt will become
prefix1suffix
but then i got an error
it's said file already exist though there's only one file on tes folder, which is 1.txt how do i make it work ? where's the error comes from ?
i have tried the following code
private void Rename(string prefix, string filepath, string suffix)
{
//i don't use prefix suffix yet to make sure if my function works
DirectoryInfo d = new DirectoryInfo(filepath);
FileInfo[] file = d.GetFiles();
try
{
foreach (FileInfo f in file )
{
File.Move(f.FullName,"stackoverflow");
}
}
catch (Exception e)
{
cmd.cetakGagal(e.ToString(), title);
}
cmd.cetakSukses("Rename Success", title);
}
and it returns same error as the second picture above.
the following picture is tes folder, there's nothing in tes folder except 1.txt
You are calling File.Move() with a full path for your sourceFileName and a relative path for your destFileName. The relative file path is relative to the current working directory and not to the source file path. I expect that a stackoverflow file exists in the current working directory, most likely created the first time you ran this code.
your File.Move is changing them all to StackOverflow not using the prefix and suffix. If you only have one file in the directory it shouldn't be an issue. Are you sure there is only 1 file?
public static void Move(
string sourceFileName,
string destFileName
)
Looking at this answer might be the clue as you are specifying relative path for the destination file. To obtain the current working directory, see GetCurrentDirectory
The sourceFileName and destFileName arguments are permitted to specify
relative or absolute path information. Relative path information is
interpreted as relative to the current working directory.
You should change
File.Move(f.FullName,"stackoverflow");
to
string fileName = f.Name.Replace(f.Extenstion,string.Empty);
string newFileName = string.Format("{0}{1}{2}",prefix,fileName,suffix);
string newFileWithPath = Path.Combine(f.Directory,newFileName);
if (!File.Exists(newFileWithPath))
{
File.Move(f.FullName,newFileWithPath);
}
The code above will give you that error since, after the first run through, "stackoverflow" exists as a file. Make sure that you check if the destination file exists (using File.Exists) before calling File.Move.
Since your goal is renaming, I would suggest using a test folder filled with files rather than using a piecemeal approach. See if something like this helps:
private void Rename(string prefix, string filepath, string suffix)
{
//i don't use prefix suffix yet to make sure if my function works
DirectoryInfo d = new DirectoryInfo(filepath);
FileInfo[] file = d.GetFiles();
try
{
foreach (FileInfo f in file )
{
f.MoveTo(#filepath + #"\" + prefix + f.Name.Insert(f.Name.LastIndexOf('.'),suffix));
}
}
catch (Exception e)
{
cmd.cetakGagal(e.ToString(), title);
}
cmd.cetakSukses("Rename Success", title);
}
on a side note using a listview to display the filenames and the changes before they're committed will help prevent unwanted changes.

GetTempFileName() and saving to the AppData folder

In the below code, the files are being saved in the debug folder of the project, I want to store the files in the appdata folder under a generic specified folder!
AViewModel vm = DataContext as AViewModel;
var table = vm.FileSelectedItem;
if (table != null)
{
var filename = System.IO.Path.GetTempFileName();
File.WriteAllBytes(table.FileTitle, table.Data);
Process prc = new Process();
prc.StartInfo.FileName = table.FileTitle;
prc.Start();
}
//table.FileTitle is the name of the file stored in the db
// eg:(test1.docx, test2.pdf, test3.txt, test4.xlsx)
//table.Data is public byte[] Data { get; set; } property
// which stores the files coming from the db.
I am looking at GetFolderPath and trying something like this now
System.IO.Path.GetTempFileName(
Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData));
Thanks for any replys!
GetTempFileName returns a full path to a file in the user's temp path. You can't use that to create a file within a specific folder.
Given that you want to store within the AppData folder already, perhaps you are after something more like:
var path = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "YourCompany\\YourProduct\\Output");
var filename = Path.Combine(path, table.FileTitle);
File.WriteAllBytes(filename, table.Data);
Process.Start(filename);
In case you want to create randomly named file under AppData, you can try
Guid.NewGuid().ToString("N")
That'll give you random string with reasonable certainty it is unique. For folder under AppData:
Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), Guid.NewGuid().ToString("N"));
Note: at least put it into some subfolder, AppData is folder shared with all other apps.

How to set physical path to upload a file in Asp.Net?

I want to upload a file in a physical path such as E:\Project\Folders.
I got the below code by searching in the net.
//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);
}
But in that, I want to give my physical path as I mentioned above. How to do this?
Server.MapPath("~/Files") returns an absolute path based on a folder relative to your application. The leading ~/ tells ASP.Net to look at the root of your application.
To use a folder outside of the application:
//check to make sure a file is selected
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);
}
Of course, you wouldn't hardcode the path in a production application but this should save the file using the absolute path you described.
With regards to locating the file once you have saved it (per comments):
if (FileUpload1.HasFile)
{
string fileName = Path.Combine(#"E:\Project\Folders", FileUpload1.FileName);
FileUpload1.SaveAs(fileName);
FileInfo fileToDownload = new FileInfo( filename );
if (fileToDownload.Exists){
Process.Start(fileToDownload.FullName);
}
else {
MessageBox("File Not Saved!");
return;
}
}
Well,
you can accomplish this by using the VirtualPathUtility
// Fileupload1 is ID of Upload file
if (Fileupload1.HasFile)
{
// Take one variable 'save' for store Destination folder path with file name
var save = Server.MapPath("~/Demo_Images/" + Fileupload1.FileName);
Fileupload1.SaveAs(save);
}

Categories

Resources