how to concatenate value of dropdown list - c#

I have three dropdown lists. From these three I have to select various path to retrieve one folder. The problem is path can't retrieve the folder and give error can't find a part of path. My code for that is.
protected void Btn_Load_Click1(object sender, EventArgs e)
{
string _username = ConfigurationManager.AppSettings["ImpersonatedUserName"].ToString();
string _password = ConfigurationManager.AppSettings["ImpersonatedPassword"].ToString();
string _domain = ConfigurationManager.AppSettings["ImpersonatedDomain"].ToString();
Impersonation objImpersonation = new Impersonation();
if (objImpersonation.impersonateValidUser(_username, _domain, _password))
{
string PathFecha = ConfigurationManager.AppSettings.ToString() + "\\Convert.ToString(Drp_List1.SelectedItem)\\Convert.ToString(Drp_List2.SelectedItem)\\Convert.ToString(Drp_List3.SelectedItem)\\";
string[] files = System.IO.Directory.GetFiles(PathFecha);
foreach (string filename in files)
{
ListBox1.Items.Add(new ListItem(System.IO.Path.GetFileName(filename), filename));
}
}
}

You are not converting the paths properly.
Change this line:
string PathFecha = ConfigurationManager.AppSettings.ToString() + "\\Convert.ToString(Drp_List1.SelectedItem)\\Convert.ToString(Drp_List2.SelectedItem)\\Convert.ToString(Drp_List3.SelectedItem)\\";
TO:
string PathFecha = string.Format("{0}{4}{1}{4}{2}{4}{3}{4}", ConfigurationManager.AppSettings.ToString(), Drp_List1.SelectedText, Drp_List2.SelectedText, Drp_List3.SelectedText, "\\");

Use Drp_List1.SelectedItem.Text if you need Text of selected dropdown menu item.
Use Drp_List1.SelectedItem.Value if you need Value of selected dropdown menu.
Do this for all dropdowns.

string PathFecha =
System.IO.Path.Combine(
ConfigurationManager.AppSettings.ToString(),
Drp_List1.SelectedItem.Text,
Drp_List2.SelectedItem.Text,
Drp_List3.SelectedItem.Text);
Using Path.Combine() may make it a little easier dealing with the paths.

Well it looks to me that with this line:
string PathFecha = ConfigurationManager.AppSettings.ToString() + "\\Convert.ToString(Drp_List1.SelectedItem)\\Convert.ToString(Drp_List2.SelectedItem)\\Convert.ToString(Drp_List3.SelectedItem)\\";
you are simply concatenating a single string to the base path, which is not what you want. Putting C# code into a string won't replace the result of that code in the string. What you want to do is concatenate each part of the path individually:
string PathFecha = Convert.ToString(Drp_List1.SelectedItem) + "\\"
+ Convert.ToString(Drp_List2.SelectedItem) + "\\"
+ Convert.ToString(Drp_List3.SelectedItem) + "\\";
And, as Gloria said, if you want to use the text of the selected item, you should use Drp_List1.SelectedItem.Text. So it should actually be:
string PathFecha = Drp_List1.SelectedItem.Text + "\\"
+ Drp_List2.SelectedItem.Text + "\\"
+ Drp_List3.SelectedItem.Text + "\\";

Related

Moving files to corresponding folder [duplicate]

This question already has an answer here:
Moving files using SSIS and Script Component
(1 answer)
Closed 4 years ago.
I'm using C# language for finding certain files and moving them to corresponding folder. I'm using this code bellow, but files that I'm getting lately cannot be read with this code. Before name of the file would be for example "File_20141120", but files that I'm getting now are named, for example: ABC (222), ACD (2), DES (33), so I need to write a code that will read numbers in parentheses and move it to folder with the same number.
The code I'm using right now:
public void Main()
{
string filename;
string datepart;
bool FolderExistFlg;
filename = Dts.Variables["User::FileName"].Value.ToString();
datepart = (filename.Substring(filename.Length - 12)).Substring(0, 8);
FolderExistFlg = Directory.Exists(Dts.Variables["OutputMainFolder"].Value.ToString() + "\\" + datepart);
if (!FolderExistFlg)
{
Directory.CreateDirectory(Dts.Variables["OutputMainFolder"].Value.ToString() + "\\" + datepart);
}
File.Move(Dts.Variables["SourceFolder"].Value.ToString() + "\\" + filename,
Dts.Variables["OutputMainFolder"].Value.ToString() + "\\" + datepart + "\\" + filename);
Dts.TaskResult = (int)ScriptResults.Success;
}
#region ScriptResults declaration
enum ScriptResults
{
Success = Microsoft.SqlServer.Dts.Runtime.DTSExecResult.Success,
Failure = Microsoft.SqlServer.Dts.Runtime.DTSExecResult.Failure
};
#endregion
}
}
SSIS is optimized for the task you are performing. If we assume that all files in the source folder need to be moved, then place the file task in a for each loop and parameterize the source and destination variables.
Create five variables:
SourceFolder
DestinationFolder
FileName
SourceFileNameWithPath = SourceFolder + "\" + FileName
DestinationFileNameWithPath = DestinationFolder + "\" + FileName
Use the ForEach loop to loop over the SourceFolder and read in each file name (select File Name and Extension) into the FileName variable (note: set FileSpec to either . or *.) . In the File Task, set the source variable to SourceFileNameWithPath and the destination variable to DestinationFileNameWithPath.
The File System Task should be Rename File.
https://www.tutorialgateway.org/move-multiple-files-using-file-system-task-in-ssis/
It sounds like you're asking how to extract the folder name from between the two parens (). If that's the case, a simple RegEx will work for you:
// Extracts only the number between the parens
// E.g. Filename: aaa (333)
// Output: 333
var folderNumber = Regex.Match(
filename,
#"\(([^)]*)\)").Groups[1].Value;

How to add '/' between two strings?

I have the following code:
if (!string.IsNullOrEmpty(_location.FolderName))
{
name = _location.FolderName + '/' + name;
}
Is it correct way to add / between two strings? Or I should use the following code:
if (!string.IsNullOrEmpty(_location.FolderName))
{
name = _location.FolderName + "/" + name;
}
For concatenating file paths, you should use the System.IO.Path.Combine method instead.
using System.IO;
...
if (!string.IsNullOrEmpty(_location.FolderName))
{
name = Path.Combine(_location.FolderName, name);
}
One thing to note, as Anton mentioned in the comments below is that you must ensure that the characters in the paths are valid, you can find more information in the documentation.
Use Path.DirectorySeparatorChar for this purpose: https://msdn.microsoft.com/ru-ru/library/system.io.path.pathseparator%28v=vs.110%29.aspx?f=255&MSPPError=-2147217396
Console.WriteLine("Path.AltDirectorySeparatorChar={0}", Path.AltDirectorySeparatorChar);
Console.WriteLine("Path.DirectorySeparatorChar={0}", Path.DirectorySeparatorChar);
Console.WriteLine("Path.PathSeparator={0}", Path.PathSeparator);
Console.WriteLine("Path.VolumeSeparatorChar={0}", Path.VolumeSeparatorChar);
Console.Write("Path.GetInvalidPathChars()=");
foreach (char c in Path.GetInvalidPathChars())
Console.Write(c);
Console.WriteLine();
Will give result:
// Path.AltDirectorySeparatorChar=/
// Path.DirectorySeparatorChar=\
// Path.PathSeparator=;
// Path.VolumeSeparatorChar=:
Use double back slash it will help
if (!string.IsNullOrEmpty(_location.FolderName))
{
name = _location.FolderName + "\\" + name;
}

How to specify a file path in ASP.NET MVC

I want to specify a virtual path of a file but I am not able to do so.
Here is my code:
int Course_Id = 1;
int PortfolioID=1;
int ChandidateID=1;
string filepath = Server.MapPath("~/ePortfolio/PortFolioContent/" + Course_Id + "/Assignments/Exhb_" + item.PortfolioID + "_" + item.ChandidateID + ".jpg");
if(System.IO.File.Exists((filepath)))
{
ViewBag.Thumbnail = filepath;
}
When i use Server.MapPath it is fetching data from some other path:
My original path is:
E:\HOBBYHOMES(E-PORTFOLIO)\HobbyHomesWebApp\ePortfolio\PortFolioContent\1\Assignments
but it is taking this path
E:\HOBBYHOMES(E-PORTFOLIO)\HobbyHomesWebApp\ActivityPostin\Images\ePortfolio\PortFolioContent\1\Assignments\Exhb_1_1.jpg
I m not understanding why this is workin so.Please help me
Try string filepath = Server.MapPath("~/... ...jpg");
You can use #Url.Content("~/Content/Images/YourImageName.png")
Try doing something like this:
Path.Combine(Server.MapPath("~/"),("ePortfolio\\PortFolioContent\\" + Course_Id + "\\Assignments\\Exhb_" + item.PortfolioID + "_" + item.ChandidateID + ".jpg"));
In theory it results in the same answer that failed you previously. In practice, it may yield a completely different answer.
There's also a recent question here (which I can't find at the moment) which highlights that sometimes Server.MapPath("~/..etc..") misbehaves on rewritten request paths. Are you rewriting the request that is trying to form this path?

Remove part of the full directory name?

I have a list of filename with full path which I need to remove the filename and part of the file path considering a filter list I have.
Path.GetDirectoryName(file)
Does part of the job but I was wondering if there is a simple way to filter the paths using .Net 2.0 to remove part of it.
For example:
if I have the path + filename equal toC:\my documents\my folder\my other folder\filename.exe and all I need is what is above my folder\ means I need to extract only my other folder from it.
UPDATE:
The filter list is a text box with folder names separated by a , so I just have partial names on it like the above example the filter here would be my folder
Current Solution based on Rob's code:
string relativeFolder = null;
string file = #"C:\foo\bar\magic\bar.txt";
string folder = Path.GetDirectoryName(file);
string[] paths = folder.Split(Path.DirectorySeparatorChar);
string[] filterArray = iFilter.Text.Split(',');
foreach (string filter in filterArray)
{
int startAfter = Array.IndexOf(paths, filter) + 1;
if (startAfter > 0)
{
relativeFolder = string.Join(Path.DirectorySeparatorChar.ToString(), paths, startAfter, paths.Length - startAfter);
break;
}
}
How about something like this:
private static string GetRightPartOfPath(string path, string startAfterPart)
{
// use the correct seperator for the environment
var pathParts = path.Split(Path.DirectorySeparatorChar);
// this assumes a case sensitive check. If you don't want this, you may want to loop through the pathParts looking
// for your "startAfterPath" with a StringComparison.OrdinalIgnoreCase check instead
int startAfter = Array.IndexOf(pathParts, startAfterPart);
if (startAfter == -1)
{
// path not found
return null;
}
// try and work out if last part was a directory - if not, drop the last part as we don't want the filename
var lastPartWasDirectory = pathParts[pathParts.Length - 1].EndsWith(Path.DirectorySeparatorChar.ToString());
return string.Join(
Path.DirectorySeparatorChar.ToString(),
pathParts, startAfter,
pathParts.Length - startAfter - (lastPartWasDirectory?0:1));
}
This method attempts to work out if the last part is a filename and drops it if it is.
Calling it with
GetRightPartOfPath(#"C:\my documents\my folder\my other folder\filename.exe", "my folder");
returns
my folder\my other folder
Calling it with
GetRightPartOfPath(#"C:\my documents\my folder\my other folder\", "my folder");
returns the same.
you could use this method to split the path by "\" sign (or "/" in Unix environments). After this you get an array of strings back and you can pick what you need.
public static String[] SplitPath(string path)
{
String[] pathSeparators = new String[]
{
Path.DirectorySeparatorChar.ToString()
};
return path.Split(pathSeparators, StringSplitOptions.RemoveEmptyEntries);
}

How to get only directory name from SaveFileDialog.FileName

What would be the easiest way to separate the directory name from the file name when dealing with SaveFileDialog.FileName in C#?
Use:
System.IO.Path.GetDirectoryName(saveDialog.FileName)
(and the corresponding System.IO.Path.GetFileName). The Path class is really rather useful.
You could construct a FileInfo object. It has a Name, FullName, and DirectoryName property.
var file = new FileInfo(saveFileDialog.FileName);
Console.WriteLine("File is: " + file.Name);
Console.WriteLine("Directory is: " + file.DirectoryName);
The Path object in System.IO parses it pretty nicely.
Since the forward slash is not allowed in the filename, one simple way is to divide the SaveFileDialog.Filename using String.LastIndexOf; for example:
string filename = dialog.Filename;
string path = filename.Substring(0, filename.LastIndexOf("\"));
string file = filename.Substring(filename.LastIndexOf("\") + 1);

Categories