I have some problem with my open new window popup which it can read my path and it like throw away my "/" sign in it. So it will be see like this "C:UsersKHAIRADesktopheitechHibah Total v1.2/Secure/PDF Folder"
Can anyone help me to make it look/read like this "C:Users/KHAIRA/Desktop/heitech/Hibah Total v1.2/Secure/PDF Folder".
I have open button in gridview that will open new window and view the pdf file here the coding from ViewDocument.aspx
string commandName = e.CommandName.ToString().Trim();
GridViewRow row = GridView1.Rows[Convert.ToInt32(e.CommandArgument)];
string folderName = ConfigurationManager.AppSettings["folderPDF"].ToString();
string path = Server.MapPath("~") + "/Secure/";
string fullPath = path + folderName;
string[] filePaths = Directory.GetFiles(fullPath, "*.pdf");
switch (commandName)
{
case "Open":
string script = "<script language=\"JavaScript\">\n";
script += "window.open ('OpenForm.aspx?path=" + row.Cells[0].Text;
script += "','CustomPopUp', config='height=500,width=1024, toolbar=no, menubar=no, scrollbars=yes, resizable=yes,location=no, directories=no, status=no')\n";
script += "</script>";
this.ClientScript.RegisterStartupScript(this.GetType(), "onload", script);
break;
for the OpenForm.aspx.cs coding :
catch(Exception ex)
{
try
{
string paths = Request.QueryString["path"].ToString();
bool fileExist = File.Exists(paths);
if (fileExist)
{
Response.ContentType = "Application/pdf";
Response.TransmitFile(paths);
}
else
{
Label1.Text = "File Not Exist";
}
}
However, i realize that the problem is from here
string paths = Request.QueryString["path"].ToString();
First things first.
The local system path separator is \ e.g. C:\Windows.
/ is for web e.g. http://stackoverflow.com/questions/9902129/how-to-make-the-path-have/9902194#9902194
For a single \ you have to put \\ (remember escape sequence)
Or
Use String Verbatim
string path = #"C:\Users\KHAIRA\Desktop\heitech\Hibah Total v1.2\Secure\PDF Folder"
Or
Use Path.Combine method of System.IO namespace like
Path.Combine("C:", "Users");
It will give return a string
C:\Users
Try to use something like this:
string path = "C:Users\\KHAIRA\\Desktop\\heitech\\Hibah Total v1.2\\Secure\\PDF Folder";
Try this
String path=#"C:Users/KHAIRA/Desktop/heitech/Hibah Total v1.2/Secure"
String fullpath=path + "\\\" + "PDF Folder"
Fullpath will contain the path you want
Related
please help me. I would like to create new folder and save a screenshots from selenium therein.
I want, when I click the button xxx_1, folder will automatically be created with text which I enter in txt_Box1 and currently date.
Folder should be looks like that:
Test_test2_18_test3-test4_test5_test_11-Jul-2017
Here's my code
private void xxx_1(object sender, EventArgs e)
{
string path = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData)
+ "C:/xxx/xxx" + "_" + textBox1 + "_" + "xxx_xxx_xx_" + DateTime.Now;
if (!Directory.Exists(path))
{
Directory.CreateDirectory(path);
}
//string path = #"C:\\xxx\xxx" + "_" + textBox1 + "_" + "xxx_xxx_xxx_" + DateTime.Now;
String xxx= "https://xxx.xxx.xxx";
IWebDriver driver_xx = new ChromeDriver();
driver_xx.Navigate().GoToUrl(xxx);
driver_xx.FindElement(By.Id("xxx")).SendKeys("xxx");
driver_xx.FindElement(By.Id("xx")).SendKeys("xxx");
driver_xx.FindElement(By.Id("xx")).Click();
Thread.Sleep(3000);
Screenshot ss_xx = ((ITakesScreenshot)driver_xx).GetScreenshot();
ss_xx.SaveAsFile("How to save the screenshots in new created folder??", OpenQA.Selenium.ScreenshotImageFormat.Jpeg);
}
You can't use a DateTime in your path like that as the default implementation of .ToString() on a DateTime will contain invalid characters. Use a format specifier:
string path = Path.Combine(
Environment.GetFolderPath(Environment.SpecialFolder.Desktop),
"xx\\xx",
textBox1.Text,
"xx_xxx_xxx_",
DateTime.Now.ToString("dd-MM-yyyy HH-mm-ss") // This will show '21-09-2017 16-11-15'
);
Directory.CreateDirectory(path);
Be careful that if textBox1.Text contains invalid path characters such as < > : then you'll get another exception.
Suppose i have a folder and in this folder is an image named im1.png. i want that im1.png is deleted when i save another image named im1.jpg or im1.bmp or so on...(same name but different type) in this folder. i write following code but this code just delete file that has same name and same type. Help me please...
string CopyPic(string MySourcePath, string key, string imgNum)
{
string curpath;
string newpath;
curpath = Application.Current + #"\FaceDBIMG\" + key;
if (Directory.Exists(curpath) == false)
Directory.CreateDirectory(curpath);
newpath = curpath + "\\" + imgNum + MySourcePath.Substring(MySourcePath.LastIndexOf("."));
string[] similarFiles = Directory.GetFiles(curpath, imgNum + ".*").ToArray();
foreach (var similarFile in similarFiles)
File.Delete(similarFile);
File.Copy(MySourcePath, newpath);
return newpath;
}
Here is one way to do it:
string filename = ...; //e.g. c:\directory\filename.ext
//Get the directory where the file lives
string dir = Path.GetDirectoryName(filename);
//Get the filename without the extension to use it to search the directory for similar files
string filenameWithoutExtension = Path.GetFileNameWithoutExtension(filename);
//Search the directory for files with same name, but with any extension
//We use the Except method to remove the file it self form the search results
string[] similarFiles =
Directory.GetFiles(dir, filenameWithoutExtension + ".*")
.Except(
new []{filename},
//We should ignore the case when we remove the file itself
StringComparer.OrdinalIgnoreCase)
.ToArray();
//Delete these files
foreach(var similarFile in similarFiles)
File.Delete(similarFile);
In my Windows application, I have a PictureBox and a Button control. I want to load an Image file from user from the button's OnClick event and save that image file in a folder name "proImg" which is in my project. Then I want to show that image in the PictureBox.
I have written this code, but it is not working:
OpenFileDialog opFile = new OpenFileDialog();
opFile.Title = "Select a Image";
opFile.Filter = "jpg files (*.jpg)|*.jpg|All files (*.*)|*.*";
if (opFile.ShowDialog() == DialogResult.OK)
{
try
{
string iName = opFile.FileName;
string filepath = "~/images/" + opFile.FileName;
File.Copy(iName,Path.Combine("~\\ProImages\\", Path.GetFileName(iName)));
picProduct.Image = new Bitmap(opFile.OpenFile());
}
catch (Exception exp)
{
MessageBox.Show("Unable to open file " + exp.Message);
}
}
else
{
opFile.Dispose();
}
It's not able to save the image in the "proImg" folder.
Actually the string iName = opFile.FileName; is not giving you the full path. You must use the SafeFileName instead. I assumed that you want your folder on your exe directory also. Please refer to my modifications:
OpenFileDialog opFile = new OpenFileDialog();
opFile.Title = "Select a Image";
opFile.Filter = "jpg files (*.jpg)|*.jpg|All files (*.*)|*.*";
string appPath = Path.GetDirectoryName(Application.ExecutablePath) + #"\ProImages\"; // <---
if (Directory.Exists(appPath) == false) // <---
{ // <---
Directory.CreateDirectory(appPath); // <---
} // <---
if (opFile.ShowDialog() == DialogResult.OK)
{
try
{
string iName = opFile.SafeFileName; // <---
string filepath = opFile.FileName; // <---
File.Copy(filepath, appPath + iName); // <---
picProduct.Image = new Bitmap(opFile.OpenFile());
}
catch (Exception exp)
{
MessageBox.Show("Unable to open file " + exp.Message);
}
}
else
{
opFile.Dispose();
}
You should provide a correct destination Path to File.Copy method. "~\ProImages..." is not a correct path. This example will copy selected picture to folder ProImages inside the project's bin folder :
string iName = opFile.FileName;
File.Copy(iName, Path.Combine(#"ProImages\", Path.GetFileName(iName)));
the path is relative to current executable file's location, except you provide full path (i.e. #"D:\ProImages").
In case you didn't create the folder manually and want the program generate ProImages folder if it doesn't exist yet :
string iName = opFile.FileName;
string folder = #"ProImages\";
var path = Path.Combine(folder, Path.GetFileName(iName))
if (!Directory.Exists(folder))
{
Directory.CreateDirectory(folder);
}
File.Copy(iName, path);
PS: Notice the use of verbatim (#) to automatically escape backslash (\) characters in string. It is common practice to use verbatim when declaring string that represent path.
Try using picturebox.Image.Save function. In my program it is working
PictureBox.Image.Save(Your directory, ImageFormat.Jpeg)
example
pictureBox2.Image.Save(#"D:/CameraImge/"+foldername+"/"+ numbering + ".jpg", ImageFormat.Jpeg);
You write code like this.
string appPath = Path.GetDirectoryName(Application.ExecutablePath) +foldername ;
pictureBox1.Image.Save(appPath + #"\" + filename + ".jpg", ImageFormat.Jpeg);
Getting this error The given path's format is not supported. at this line
System.IO.Directory.CreateDirectory(visit_Path);
Where I am doing mistake in below code
void Create_VisitDateFolder()
{
this.pid = Convert.ToInt32(db.GetPatientID(cmbPatientName.SelectedItem.ToString()));
String strpath = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location);
String path = strpath + "\\Patients\\Patient_" + pid + "\\";
string visitdate = db.GetPatient_visitDate(pid);
this.visitNo = db.GetPatientID_visitNo(pid);
string visit_Path = path +"visit_" + visitNo + "_" + visitdate+"\\";
bool IsVisitExist = System.IO.Directory.Exists(path);
bool IsVisitPath=System.IO.Directory.Exists(visit_Path);
if (!IsVisitExist)
{
System.IO.Directory.CreateDirectory(path);
}
if (!IsVisitPath)
{
System.IO.Directory.CreateDirectory(visit_Path);\\error here
}
}
getting this value for visit_Path
C:\Users\Monika\Documents\Visual Studio 2010\Projects\SonoRepo\SonoRepo\bin\Debug\Patients\Patient_16\visit_4_16-10-2013 00:00:00\
You can not have : in directory name, I suggest you to use this to string to get date in directory name:
DateTime.Now.ToString("yyyy-MM-dd hh_mm_ss");
it will create timestamp like:
2013-10-17 05_41_05
additional note:
use Path.Combine to make full path, like:
var path = Path.Combine(strpath , "Patients", "Patient_" + pid);
and last
string suffix = "visit_"+visitNo+"_" + visitdate;
var visit_Path = Path.Combine(path, suffix);
In general always use Path.Combine to create paths:
String strPath = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location);
String path = Path.Combine(strPath,"Patients","Patient_" + pid);
string visitdate = db.GetPatient_visitDate(pid);
this.visitNo = db.GetPatientID_visitNo(pid);
string fileName = string.Format("visit_{0}_{1}", visitNo, visitdate);
string visit_Path = Path.Combine(path, fileName);
bool IsVisitExist = System.IO.Directory.Exists(path);
bool IsVisitPath=System.IO.Directory.Exists(visit_Path);
To replace invalid characters from a filename you could use this loop:
string invalidChars = new string(Path.GetInvalidFileNameChars()) + new string(Path.GetInvalidPathChars());
foreach (char c in invalidChars)
{
visit_Path = visit_Path.Replace(c.ToString(), ""); // or with "."
}
You can't have colons : in file paths
You can't use colons (:) in a path. You can for example Replace() them with dots (.).
Just wanted to add my two cents.
I assigned the path from a text box to string and also adding additional strings, but I forgot to add the .Text to the text box variable.
So instead of
strFinalPath = TextBox1.Text + strIntermediatePath + strFilename
I wrote
strFinalPath = TextBox1 + strIntermediatePath + strFilename
So the path became invalid because it contained invalid characters.
I was surprised that c# instead of rejecting the assignment because of type mismatch, assigned invalid value to the final string.
So look at the path assignment string closely.
I'm trying to save files
string path= "~/Pre/IntraExtra/" + Session["id"].ToString() + "_" + FileUpload1.FileName;
FileUpload11.SaveAs(Server.MapPath(path));
but it gives this error "The given path's format is not supported."
It is working now ..
I just removed the (~/) , Thank you all
for example if I had code that was set like the following on my end it works.. also notice the # symbol I am using .. this is for a literal file path this way I don't have to use "\ in the file path.. try the following code as see if it works.. replace with your code variables.
if (FileUpload1.HasFile)
{
fname = FileUpload1.FileName;
spath = "~\Pre\IntraExtra\" + FileUpload1.FileName;
fpath = Server.MapPath("Uploaded");
fpath = fpath + #"\" + FileUpload1.FileName;
desc = TextBox2.Text;
if (System.IO.File.Exists(fpath))
{
Label1.Text = "File Name already exists!";
return;
}
else
{
FileUpload1.SaveAs(fpath);
}
}
Maybe try to use the Path.Combine method:
string path= "~/Pre/IntraExtra/" + Session["id"].ToString() + "_"; ;
string combinedPath = System.IO.Path.Combine(path, FileUpload1.FileName);
FileUpload11.SaveAs(Server.MapPath(combinedPath));
If this does not work, then could you give us the filename and path?
It is working now .. I just removed the (~/) , Thank you all