Could not find file 'c:\windows\system32\inetsrv\ - c#

I am using a aspx webpage with C# and I'm trying to point to a directory but when I do so, I get "Could not find file 'c:\windows\system32\inetsrv\2.txt'." But in my C# code, I am using:
currentStaffPosition = rolesRadioButton.SelectedItem.ToString();
string currentStaffDirectory = Server.MapPath(#"~\admin\applications\" + currentStaffPosition);
This code should point to C:\inetpub\wwwroot\admin\applications
Anyone know why or how this is happening? Thanks ahead of time.
Additional Code:
string currentStaffPosition = null;
string currentStaffDirectory = null;
protected void rolesRadioButton_SelectedIndexChanged(object sender, EventArgs e)
{
dropDownList.Items.Clear();
currentStaffPosition = rolesRadioButton.SelectedItem.ToString();
string currentStaffDirectory = Server.MapPath(#"~\admin\applications\" + currentStaffPosition);
string[] staffApplications = Directory.GetFiles(currentStaffDirectory);
foreach (string apps in staffApplications)
{
dropDownList.Items.Add(new ListItem(Path.GetFileNameWithoutExtension(apps)));
}
}
protected void dropDownList_SelectedIndexChanged(object sender, EventArgs e)
{
string currentSelectedApp = currentStaffDirectory + dropDownList.SelectedItem + ".txt";
string currentLine;
StreamReader applicationReader = new StreamReader(currentSelectedApp);
while ((currentLine = applicationReader.ReadLine()) != null)
{
if (currentLine.Contains("First Name:"))
forumUsernameTextBox.Text = currentLine.Replace("First Name: ", "");
}
applicationReader.Close();
}

Related

Changing the Path of a file from a User's Input on a form in C#

My user can create a file name that goes to a specific directory path(Textbox3) and they can change the directory path(TextBox4), I am having trouble reading Textbox4 which is the changing the path textbox.
It reads textbox3 just fine and does everything i need it to do if there is a filename in the textbox but when i put something in textbox4 it is not reading it.
private void textBox3_TextChanged(object sender, EventArgs e) //reads fine, file goes to C:\\Temp
{
string textBoxContents = textBox3.Text;
}
private void textBox4_TextChanged(object sender, EventArgs e)//this is not required, this is only if they want to change where the file is going Ex:(D:\\Test
{
string textBoxContents = textBox4.Text;
}
private void button1_Click(object sender, EventArgs e)
{
string Filename = textBox3.Text.Substring(0) + ".txt";
string Filepath = textBox4.Text.Substring(0) + ".txt";
var files = Directory.GetFiles(#"C:\\Temp").Length;
string path2 = Path.GetFullPath("C:\\Temp");
string docPath = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
string var = Path.Combine(docPath, path2);
string var1 = Path.Combine(var, Filename);
using (StreamWriter objWriter = new StreamWriter(var1))
{
int numpins = int.Parse(textBox1.Text);
string basepin = textBox2.Text;
int pinlength = basepin.Length;
string formatspecifier = "{0:d" + pinlength.ToString() + "}" + "{1}";
long pinnumber = long.Parse(basepin);
string dig = textBox2.Text;
string result = GetCheckDigit(dig);
objWriter.WriteLine($"These are the Bin ranges");
objWriter.WriteLine();
for (int d = 0; d < numpins; d++)
{
if (String.IsNullOrEmpty(dig))
{
throw new Exception("null value not allowed");
}
else
{
dig = pinnumber.ToString();
result = GetCheckDigit(dig);
}
basepin = string.Format(formatspecifier, pinnumber, result);
objWriter.WriteLine(basepin);
pinnumber++;
}
objWriter.Close();
MessageBox.Show("File has been created");
}
}

Load JSON File to ListBox and TextBox C#

I'm working on a Windows Form Application. Textbox index can be saved and shown as in ListBox with this code:
private List<FunctionData> funcParamList = new List<FunctionData>();
...
private void addFuncButton_Click(object sender, EventArgs e)
{
FunctionData funcParams = new FunctionData();
funcParams.blabla1name = blabla1.Text;
funcParams.blabla2name = blabla2.Text;
...
if (funcParams.isValid())
{
funcParamList.Add(funcParams);
functionListBox.Items.Add(functionNameBox.Text);
}
Also I collect objects to TextBox again to edit (by clicking ListBox item) with the following code :
private void getParams(FunctionData data)
{
blabla1.Text = data.blabla1name;
blabla2.Text = data.blabla2name;
functionNameBox.Text = data.functionName;
return;
}
private void functionListBox_SelectedIndexChanged(object sender, EventArgs e)
{
if (functionListBox.SelectedItem == null) { return; }
foreach (var obj in funcParamList)
{
if (obj.functionName == functionListBox.SelectedItem.ToString())
{
getParams(obj);
}
}
}
And save them to file as JSON with:
private void saveFileButton_Click(object sender, EventArgs e)
{
fileName = fileNameBox.Text;
string jsonFunc = JsonConvert.SerializeObject(funcParamList);
System.IO.File.WriteAllText(#"<blablapath>\" + fileName + ".txt", jsonFunc);
}
There's 'functionName' object in JSON file that I can use it for showing on ListBox.
My question is: How can I load this file buy Native Load/Open File Dialog and show the objects in ListBox and can edit them again?
And here how I've tried to make it with the following code, but it doesn't work:
private void loadFileButton_Click(object sender, EventArgs e)
{
OpenFileDialog loadFileDialog = new OpenFileDialog();
...
if (loadFileDialog.ShowDialog() == DialogResult.OK)
{
string jsonFileName = loadFileDialog.FileName;
string jsonFile = File.ReadAllText(jsonFileName);
dynamic loadedFile = JsonConvert.DeserializeObject(jsonFile);
//if (functionListBox.SelectedItem == null) { return; }
foreach (var obj in loadedFile)
{
if (obj.functionName != null)
{
functionListBox.Items.Add(obj.functionName);
getParams(obj); // I get exception here
funcParamList.Add(loadedFile);
functionListBox.Refresh();
}
}
}
I've solved the problem by casting 'DeserializeObject' as List and it's done. Here the changes:
...
var loadedFile = JsonConvert.DeserializeObject<List<FunctionData>>(jsonFile);

I have a query about checked list boxes in c#

I have set up a program that so far can browse for the location of a file that possesses data in a text file holding the locations of other files which then shows me if they exist, are missing or are a duplicate inside listboxes. The next step is to enable the user to select files in the checked list boxes and being given the option to either move or copy. I have already made buttons which allow this but I want to be able to use them for the checked boxes I the list boxes.(p.s) please ignore any comments I have made in the code they are just previous attempts of doing other things in the code.
My code so far:
namespace File_existence
{
public partial class fileForm : Form
{
private string _filelistlocation;
public fileForm()
{
InitializeComponent();
}
private void checkedListBox1_SelectedIndexChanged(object sender, EventArgs e)
{
}
public void fileForm_Load(object sender, System.EventArgs e)
{
_filelistlocation = textBox1.Text;
}
private void button1_Click(object sender, System.EventArgs e)
{
//GetDuplicates();
checkedListBox1.Items.Clear();
listBox2.Items.Clear();
ReadFromList();
}
private void GetDuplicates()
{
DirectoryInfo directoryToCheck = new DirectoryInfo(#"C:\\temp");
FileInfo[] files = directoryToCheck.GetFiles("*.*", SearchOption.AllDirectories);
var duplicates = files.GroupBy(x => x.Name)
.Where(group => group.Count() > 1)
.Select(group => group.Key);
if (duplicates.Count() > 0)
{
MessageBox.Show("The file exists");
FileStream s2 = new FileStream(_filelistlocation, FileMode.Open, FileAccess.Read, FileShare.Read);
// open _filelistlocation
// foreach line in _filelistlocation
// concatenate pat hand filename
//
}
}
public void ReadFromList()
{
int lineCounter = 0;
int badlineCounter = 0;
using (StreamReader sr = new StreamReader(_filelistlocation))
{
String line;
while ((line = sr.ReadLine()) != null)
{
string[] values = line.Split('\t');
if (values.Length == 2)
{
string fullpath = string.Concat(values[1], "\\", values[0]);
if (File.Exists(fullpath))
checkedListBox1.Items.Add(fullpath);
else
listBox2.Items.Add(fullpath);
++lineCounter;
}
else
++badlineCounter;
//Console.WriteLine(line);
}
}
}
//StreamReader files= new StreamReader(File)();
private void listBox1_SelectedIndexChanged(object sender, System.EventArgs e)
{
}
private void button2_Click(object sender, System.EventArgs e)
{
FolderBrowserDialog folderBrowserDlg = new FolderBrowserDialog();
folderBrowserDlg.ShowNewFolderButton = true;
DialogResult dlgResult = folderBrowserDlg.ShowDialog();
if (dlgResult.Equals(DialogResult.OK))
{
textBox1.Text = folderBrowserDlg.SelectedPath;
Environment.SpecialFolder rootFolder = folderBrowserDlg.RootFolder;
}
try
{
string fileName = "filetest1.txt";
string sourcePath = #"C:\Temp\Trade files\removed";
string targetPath = #"C:\Temp\Trade files\queued";
string sourceFile = System.IO.Path.Combine(sourcePath, fileName);
string destFile = System.IO.Path.Combine(targetPath,fileName);
System.IO.File.Copy(sourceFile, destFile, true);
}
catch (IOException exc)
{
MessageBox.Show(exc.Message);
}
}
private void button3_Click(object sender, System.EventArgs e)
{
try
{
string sourceFile = #"C:\Temp\Trade Files\queued\filetest1.txt";
string destinationFile = #"C:\Temp\Trade Files\processed\filetest1.txt";
System.IO.File.Move(sourceFile, destinationFile);
}
catch(IOException ex){
MessageBox.Show(ex.Message);//"File not found"
}
}
private void button4_Click(object sender, System.EventArgs e)
{
OpenFileDialog fileBrowserDlg = new OpenFileDialog();
//folderBrowserDlg.ShowNewFolderButton = true;
//folderBrowserDlg.SelectedPath = _filelistlocation;
fileBrowserDlg.FileName = textBox1.Text;
DialogResult dlgResult = fileBrowserDlg.ShowDialog();
if (dlgResult.Equals(DialogResult.OK))
{
textBox1.Text = fileBrowserDlg.FileName;
File_existence.Properties.Settings.Default.Save();
// Environment.SpecialFolder rootFolder = folderBrowserDlg.RootFolder;
}
}
private void button5_Click(object sender, System.EventArgs e)
{
if (!textBox1.Text.Equals(String.Empty))
{
if (System.IO.Directory.GetFiles(textBox1.Text).Length > 0)
{
foreach (string file in System.IO.Directory.GetFiles(textBox1.Text))
{
checkedListBox1.Items.Add(file);
}
}
else
{
checkedListBox1.Items.Add(String.Format("No file found: {0}", textBox1.Text));
}
}
}
}
}
The task I need to do is that the files that appear in the checked list box need to usually be moved or copied to another directory. That is fine as I can already do that with what I have coded, but what it does is it will move or copy all of the files in the checked list box. What I want to do is enable the user to only be able to select which files they what to move or copy through checking the checked list box so that only those files will be moved or copied.
EDIT: Could it be checkedListBox.checked items?

how to use AsyncFileUpload to read a file content in asp.net using c#?

i have a AsyncFileUpload control :
<asp:AsyncFileUpload ID="venfileupld" runat="server" OnUploadedComplete="ProcessUpload" />
on its OnUploadedComplete event i am writing this code :
protected void ProcessUpload(object sender, AjaxControlToolkit.AsyncFileUploadEventArgs e)
{
string name = venfileupld.FileName.ToString();
string filepath = "upload_excel/" + name;
venfileupld.SaveAs(Server.MapPath(name));
}
now i have to read the content of the uploaded file ... i have a function for that:
public void writetodb(string filename)
{
string[] str;
string vcode = "";
string pswd = "";
string vname = "";
StreamReader sr = new StreamReader(filename);
string line="";
while ((line = sr.ReadLine()) != null)
{
str = line.Split(new char[] { ',' });
vcode = str[0];
pswd = str[1];
vname = str[2];
insertdataintosql(vcode, pswd, vname);
}
lblmsg4.Text = "Data Inserted Sucessfully";
}
now my query is that how i can get the uploaded file to pass to this function ?
UPDATE
i have done this :
protected void ProcessUpload(object sender, AjaxControlToolkit.AsyncFileUploadEventArgs e)
{
string name = venfileupld.FileName.ToString();
string filepath = "upload_excel/" + name;
venfileupld.SaveAs(Server.MapPath(name));
string filename = System.IO.Path.GetFileName(e.FileName);
writetodb(filepath);
}
but getting an error... file not found
I'm not sure if i have understood the problem, but isn't it easy as:
protected void ProcessUpload(object sender, AjaxControlToolkit.AsyncFileUploadEventArgs e)
{
string name = System.IO.Path.GetFileName(e.filename);
string dir = Server.MapPath("upload_excel/");
string path = Path.Combine(dir, name);
venfileupld.SaveAs(path);
writetodb(path);
}
SaveAs will save the file on the server, so you can do what you want with it afterwards.

DropDownList1.SelectedValue is null?

I cannot get anything other than a null value from my drop down box, im trying to upload files to different directories...
public class dropDownInfo
{
public string pathName { get; set; }
public string pathValue { get; set; }
}
string uploadFolder = "";
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
// reference to directory
//DirectoryInfo di = new DirectoryInfo("//DOCSD9F1/TECHDOCS/");
DirectoryInfo di = new DirectoryInfo("D:/SMGUpload/SMGUpload/files/");
// create list of directories
List<dropDownInfo> DropDownList = new List<dropDownInfo>();
foreach (DirectoryInfo i in di.GetDirectories())
{
dropDownInfo ddInfo = new dropDownInfo();
ddInfo.pathName = i.FullName;
ddInfo.pathValue = i.FullName;
DropDownList.Add(ddInfo);
}
DropDownList1.DataSource = DropDownList;
DropDownList1.DataTextField = "pathName";
DropDownList1.DataValueField = "pathValue";
DropDownList1.DataBind();
}
}
protected void DropDownList1_IndexChanged(object sender, EventArgs e)
{
uploadFolder = DropDownList1.SelectedItem.Value;
}
protected void ASPxUploadControl1_FileUploadComplete(object sender, DevExpress.Web.ASPxUploadControl.FileUploadCompleteEventArgs e)
{
if (e.IsValid)
{
string uploadDirectory = Server.MapPath("~/files/");
//string uploadDirectory = #"\\DOCSD9F1\TECHDOCS\";
string fileName = e.UploadedFile.FileName;
//string uploadFolder = DropDownList1.SelectedValue;
//string path = (uploadDirectory + uploadFolder + "/" + fileName);
string path = Path.Combine(Path.Combine(uploadDirectory, uploadFolder), fileName);
e.UploadedFile.SaveAs(path);
e.CallbackData = fileName;
}
}
Do a check before you access the Value property.
if (DropDownList1.SelectedItem != null)
uploadFolder = DropDownList1.SelectedItem.Value;
The dropdown has no values after postback. You are only binding at first page load, then the page posts back (index changed) and the items are not re-bound.
Do you have viewstate disabled on the page or any of the controls? This could cause the issue you are describing.
Also, the local variable uploadFolder will never be preserved between post backs. You need to store it in the session or on the page somewhere.
Session["uploadFolder"] = DropDownList1.SelectedItem.Value
You need to re-set the DataSource on post back, but don't re-bind it or that will reset the selected index as well.

Categories

Resources