How to Remove ~ character from asp HyperLink - c#

I have problem how to remove /~/ character from when I save file into database my problem is when they are no file into file upload controller I grape the NavigateUrl form asp hyper link and add to savePath to save it but I get exception it couldn't find the directory
Could not find a part of the path 'C:\inetpub\wwwroot\ideaPark\DesktopModules\ResourceModule\pdf_resources\~\DesktopModules\ResourceModule\pdf_resources\New Text Document.txt'.
//save pdf docs
String savePathPDF_Resouce = #"~/DesktopModules/ResourceModule/pdf_resources/";
String savePathPDF_Vocab = #"~/DesktopModules/ResourceModule/pdf_resources/";
if (fuPDFDoc.HasFile || fupdfVocabularyURL.HasFile)
{
String fileName = fuPDFDoc.FileName;
String fileName_Vocab = fupdfVocabularyURL.FileName;
savePathPDF_Resouce += fileName;
savePathPDF_Vocab += fileName_Vocab;
fuPDFDoc.SaveAs(Server.MapPath(savePathPDF_Resouce));
fupdfVocabularyURL.SaveAs(Server.MapPath(savePathPDF_Vocab));
}
else
if (!fuPDFDoc.HasFile || !fupdfVocabularyURL.HasFile)
{
savePathPDF_Resouce += hl_doc_res.NavigateUrl.ToString();
savePathPDF_Vocab += hl_doc_vocab.NavigateUrl.ToString();
fuPDFDoc.SaveAs(Server.MapPath(savePathPDF_Resouce));
fupdfVocabularyURL.SaveAs(Server.MapPath(savePathPDF_Vocab));
}

You could use something like this to get the path:
// root filesystem path for the application (C:\inetpub\wwwroot\ideaPark)
string virtualPathRoot = AppDomain.CurrentDomain.BaseDirectory;
// path relative to the application root (/DesktopModules/ResourceModule/pdf_resources/)
string relativePath = savePathPDF_Resouce.TrimStart("~");
// save here
string targetPath = Path.Combine(virtualPathRoot, relativePath);

Related

How to search for specific text file which includes a string within the name and load data into richtextbox

How can I search for a specific text file which contains a string and then load that string into a richtextbox. Below is an example
String name = "test";
string directory = #"C:\Users\"
// search for file within directory which contains string name and then load data from text file onto the rich text box.
Firstly, you should found files. After than, you can read all file one by one and append content in to RichTextBox. I hope this helps you
string name = "test";
string[] files = Directory.GetFiles("C:\\Users")
.Where(s => s.Contains(name))
.ToArray();
RichTextBox richTextBox = new RichTextBox();
foreach (string file in files)
{
string content = File.ReadAllText(file);
richTextBox.AppendText(content);
}
I see you have found a solution, but it might be useful anyway.
This code will return the content of the first .txt file in the specified path that contains the searched pattern - if any - and add the file content to a control (a RichTextBox in this case) text.
string FilePath = #"[DirectoryPath]";
string SearchPattern = "[TextToSearch]";
DirectoryInfo dInfo = new DirectoryInfo(FilePath);
richTextBox1.Text = dInfo.GetFiles("*.txt").Select(finfo => {
string FileText = File.ReadAllText(finfo.FullName);
if (FileText.Contains(SearchPattern))
return FileText;
return string.Empty;
}).Where(s => s != string.Empty).FirstOrDefault();

rename file by adding an incrementing number to old file name c#

I'm writing my first Cocoa app in c#, its suppose to append/add numbers at the begging of a file name.
Users give only the path to the folder (for example with music), and for each file included in folder the program suppose to add incrementing numbers like
001_(old_fileName),
002_(old_fileName),
...,
092_(old_fileName)
etc,
Untill the end of files in given folder (by path).
There is no way to split a file name, cause file names are not known (may even include numbers itself). I've tried few possible options to solve this, but non of them works. Found few already asked question with changing names in c# but non of the results actually helped me.
The code under is the rest I've got at the moment, all non-working tries were firstly commented and later deleted. by NSAlert i see the path/name of each file in folder as a help. I would be more than happy to receive help
void RenameFunction()
{
string sPath = _Path_textBox.StringValue;
if (Directory.Exists(sPath))
{
var txtFiles = Directory.EnumerateFiles(sPath);
var txt2Files = Directory.GetFiles((sPath));
string fileNameOnly = Path.GetFileNameWithoutExtension(sPath);
string extension = Path.GetExtension(sPath);
string path = Path.GetDirectoryName(sPath);
string newFullPath = sPath;
int count = 1;
while (File.Exists(sPath))//newFullPath))
{
string tempFileName = string.Format(count + "_" + fileNameOnly + sPath);
//count++;
//string.Format("{0}{0}{0}{1}", fileNameOnly, count++);
newFullPath = Path.Combine(path, extension + tempFileName);
count++;
}
string[] fileEntities = Directory.GetFiles(newFullPath); //GetFileSystemEntries(sPath);//GetFiles(sPath);
//foreach (var _songName in fileEntities)
//{
// string tempFileName = count + "_" + fileNameOnly + sPath;
// //string.Format("{0}{0}{0}{1}", fileNameOnly, count++);
// newFullPath = Path.Combine(sPath ,extension + tempFileName);
// File.Move(sPath, newFullPath);
//}
foreach (var _songName in fileEntities)
{
AmountofFiles(_songName);
}
}
}
void AmountofFiles(string path)
{
var alert2 = new NSAlert();
alert2.MessageText = "mp3";
alert2.InformativeText = "AMOUNT OF MP3 FILES IS '{1}' : " + path;
alert2.RunModal();
}
Have you try use File.Move? Just move file to same path, but another name
File.Move("NameToBeRename.jpg","NewName.jpg");
There are multiple things which are not right with the code you share. The thing which want to achieve can be implemented using very simple approach.
All you need to do is retrieve all the files names with the full path from the directory and rename them one by one.
Follow the below code which demonstrates the above mentioned approach.
// Path of the directory.
var directroy = _Path_textBox.StringValue;
if (Directory.Exists(directroy))
{
//Get all the filenames with full path from the directory.
var filePaths = Directory.EnumerateFiles(directroy);
//Variable to append number in front of the file name.
var count = 1;
//Iterate thru all the file names
foreach (var filePath in filePaths)
{
//Get only file name from the full file path.
var fileName = Path.GetFileName(filePath);
//Create new path with the directory path and new file name.
var destLocation = Path.Combine(directory, count + fileName);
//User File.Move to move file to the same directory with new name.
File.Move(filePath, destLocation);
//Increment count.
count++;
}
}
I hope this helps you to resolve your issue.

Dynamic file paths and Image command

I am trying to create a file path, at the end of which will be a "images" folder that the program will use with the Image command to load jpeg files.
I want the program to dynamically know to load the jpeg files from the image folder where ever the executable is launched.
I was able to find this on this site, I added the 2 bottom code lines:
public static string AssemblyDirectory
{
get
{
string codeBase = Assembly.GetExecutingAssembly().CodeBase;
UriBuilder uri = new UriBuilder(codeBase);
string path = Uri.UnescapeDataString(uri.Path);
return System.IO.Path.GetDirectoryName(path);
}
}
public static string imagePath = #"\images";
public static string finalImagePath = AssemblyDirectory + imagePath;
If I set a break point, the 'finalImagePath' is:
"C:\Users\My Name\Documents\Visual Studio 2010\Projects\Universal Serial Diagnostics\bin\Debug\images"
Which is correct, but how do I incorporate that with:
Image image = Image.FromFile(#"C:\Users\My Name\Desktop\Dip\ENV500008.jpg");
Replacing the hard coded path with the dynamic path.
The ENV500008.jpg would be stored in the images folder.
Thank you.
string path = AppDomain.CurrentDomain.BaseDirectory + "ENV500008.jpg";
if (System.IO.File.Exists(path))
{
Image image = Image.FromFile(path);
// .. the rest of the code that uses the image ..
}
Image image = Image.FromFile(#finalImagePath + "\\ENV500008.jpg");
Image image5 = Image.FromFile(#finalImagePath + "\\ENV510829-2.jpg");
public static string GetAnyPath(string fileName)
{
//my path where i want my file to be created is : "C:\\Users\\{my-system-name}\\Desktop\\Me\\create-file\\CreateFile\\CreateFile\\FilesPosition\\firstjson.json"
var basePath = new Uri(Assembly.GetExecutingAssembly().CodeBase).LocalPath.Split(new string[] { "\\CreateFile" }, StringSplitOptions.None)[0];
var filePath = Path.Combine(basePath, $"CreateFile\\CreateFile\\FilesPosition\\{fileName}.json");
return filePath;
}
change .json to any type according to need
refer :https://github.com/swinalkm/create-file/tree/main/CreateFile/CreateFile

how to display image using imageurl in C#

if (FileUpload1.HasFile)
{
string FileName = Path.GetFileName(FileUpload1.PostedFile.FileName);
//string path = Server.MapPath(#"~\\"+Session["parentfolder"].ToString() +"\\"+ Session["brandname"].ToString() + "\\" + Seasonfolders.SelectedItem.Text + "\\" + stylefolders.SelectedItem.Text + "\\Images\\" + FileName);
string root = Server.MapPath("~");
string path = Path.GetDirectoryName(root);
string path1 = Path.GetDirectoryName(path);
string rootfolder = Path.GetDirectoryName(path1);
string imagepath = rootfolder + Session["brandname"].ToString() + "\\" + Seasonfolders.SelectedItem.Text + "\\" + stylefolders.SelectedItem.Text + "\\Images\\" + FileName;
FileUpload1.SaveAs(imagepath);
//objBAL.SaveImage("Image", Session["brandname"].ToString(), Seasonfolders.SelectedItem.Text, stylefolders.SelectedItem.Text, FileName, imagepath, Convert.ToInt32(Session["Empcode"]));
uploadedimage.ImageUrl = Server.MapPath(#"~/"+imagepath);
uploadedimage.DataBind();
}
uploadedimage is ID for Image control. The path of imagepath is E:\Folder1\Folder2\Folder3\Images\1.png
The image is getting saved but I cannot able to display the uploaded image. Do I need to add anything in this line which is to display an image ..
uploadedimage.ImageUrl = Server.MapPath(#"~/"+imagepath);
uploadedimage.DataBind();
Hosting websites or stuff on iis, does not work this way. There are a few concepts one needs to learn on that front, but the best place to start with is understand what is virtual directory.
One quote from the this page:
In IIS 7, each application must have a virtual directory, known as the
root virtual directory, and maps the application to the physical
directory that contains the application's content
So it means this is a directory where the application's "content" reside; it could be simple text files, images, etc, to complex server side pages like aspx or even classic asp, or php, etc. Now anything out of this directory is not accessible by the hosted web application.
Hence the path you intend to share doesn't work that way. There are a few options to handle this scenario.
In iis you could create a sub-virtual directory, and map its path to where your images are stored to the physical location where the images reside.
Provided your web application (when hosted on iis) has access to the path where the images reside, you can write code to read the file, and send the stream of bytes back so that your web page can render image properly.
2nd approach is usually implemented by a handler (ashx) via which you can pass the image name as query string argument, and return the bytes. Hence in short you do something like this:
uploadedImage.ImageUrl = "~/MyImageHandler.ashx?filename=foo.png" //in ur server code.
In the handler you write something like this:
public class MyImageHandler : IHttpHandler {
public void ProcessRequest (HttpContext context) {
// Comment out these lines first:
// context.Response.ContentType = "text/plain";
// context.Response.Write("Hello World");
context.Response.ContentType = "image/png";
var filepath = #"E:\your_image_dir\" + Request.QueryString["filename"];
//Ensure you have permissions else the below line will throw exception.
context.Response.WriteFile(filepath);
}
public bool IsReusable {
get {
return false;
}
}
}
The image Url in your image should be like this
"~/"+ imagepath
Try removing Server.MapPath
Try this
Create Data Folder in your root directory
if (FileUpload1.HasFile)
{
string FileName = Path.GetFileName(FileUpload1.PostedFile.FileName);
string imagepath =Server.MapPath("~/Data/"+FileName);
FileUpload1.SaveAs(imagepath);
uploadedimage.ImageUrl="~/"+imagepath;
}

Image saving into database from a folder and get back into the UI

I have a field in my app (c#) to save an image into the database. I written the following code to save the image into a folder and then save the path into the database. But the image is not getting saved into the folder.
string imgName = FileUpload1.FileName.ToString();
string imgPath = null;
if (imgName == "")
{
//int taxiid = Convert.ToInt32(HiddenField1.Value);
Taxi t = null;
t = Taxi.Owner_GetByID(tx.Taxi_Id, USM.OrgId);
imgPath = t.CarImage;
}
else
{
imgPath = "ImageStorage/" + imgName;
}
FileUpload1.SaveAs(Server.MapPath(imgPath));
tx.CarImage = imgPath;
I think your problem is that you add the name to the Path I try it and for me it works fine if I save it like this:
FileUpload1.SaveAs(Server.MapPath("ImageStorage") + imgName);
And as #Rahul mentioned add a try catch to prevent errors.
And you check
if (imgName == "")
According to my understanding it's not posible that imgName is "" but anyway you better add a check if the fileupload has a file.
if (FileUploadControl.HasFile)

Categories

Resources