Conditional file listing on gridView in ASP.NET? - c#

I am writing a file management web page for a friend of mine. I select the folder using a DropDownlist element. When the index changed it populates gridview.
For preventing user slips, I have decided not to delete the file when Delete button is clicked. I change the name of the deleted file adding a suffix.
For example if I delete a file.pdf via Deletebutton, it is renamed as file.pdf_zkanoca_deleted_1411472294
After populating the gridview content, renamed files are still listed. My listFiles() method is as the following:
public void listFiles(string selectedFolder)
{
var dir = new DirectoryInfo(selectedFolder);
gridView1.DataSource = dir.GetFiles();
gridView1.DataBind();
}
What I want is to check whether filename contains "_zkanoca_deleted_" string before binding data source to gridview. If it contains that string it will not be listed.
I think a foreach loop will solve my problem. But I could not imagine how to structure it.

Use the IEnumerable.Where extension
gridView1.DataSource = dir.GetFiles().Where(x => !x.Name.Contains("_zkanoca_deleted_")).ToList();
As explained in the docs the Where extension filters a sequence using a predicate.
In this case you could use the FileInfo property Name to check if it contains the forbidden substring and exclude that FileInfo from the sequence binded to the gridview.

Related

How to get list of .xlsx file in C#

I am developing Windows Form application and I want to have a list of .xlsx files in the folder say -
C:\Equipment\Exchanger\AES\
The folder may contain files like -
00-E-001,
00-E-002,
03-E-005,
04-E-001 and so on..
I don't want to open file dialogs but want to see a combo box showing the FileName (no extension). Based on selection of combobox I want to show the values of certain cells in the various text boxes but that is later part.
You can use Directory.GetFiles to query the full path strings of every *.xlsx file in the folder, then strip it down to just the filename using Select and Path.GetFileName.. It makes sense (to me) to sort them alphabetically, then you just need them in a list so the combo can use them
yourCombo.DataSource = Directory.GetFiles(yourFolderPath, "*.xlsx").Select(Path.GetFileName).OrderBy(n => n.ToLower()).ToList();
If you don't want the extension in the combo (it's a waste of pixels :) ) you can use Path.GetFileNameWithoutExtension
When the time comes to get which file was selected by the user it's:
var fullPath = Path.Combine(yourFolderPath, yourCombo.SelectedItem);
(You'll have to add the extension back on if you used GetFilenameWithoutExtension: yourCombo.SelectedItem + ".xlsx")
I recommend you set your combo's DropDownStyle to DropDownList
First of all, your code should have a look at the folder, which contains needed files.
List<string> xlsxFiles = Directory.GetFiles(yourdirectory, "*.*", SearchOption.AllDirectories)
.Where(file => new string[] { ".xlsx" }
.Contains(Path.GetExtension(file)))
.ToList(); // Looking into directory and filtering files
for(int i = 0; i < xlsxFiles.Count; i++)
{
xlsxFiles[i] = Path.GetFileName(Path.ChangeExtension(xlsxFiles[i], null)); // Removes files' extensions
}
This is the simple way of looking into the directory and filtering files to needed ones.
Then, I suggest having a look into EPPlus library, which allows you to work directly with tables and cells, without manual extraction of the file
Here is the handy tutorial of using EPPlus

C# SharePoint CSOM: Update multiline text field

I wrote a little C# app to retrieve data from several SP custom lists. This has been going very smoothly for months. Now I updated my app to alter some items. To be exact I like to update one multiline text field for some items. Here is my code:
// Update SharePoint list elements
foreach (var o in toWrite) // List<(int, string)>();
{
List destList = ctx.Web.Lists.GetByTitle(listToUpdate); // listToUpdate: SP list name
ListItem listItem = destList.GetItemById(o.Item1); // o.Item1: id to update
listItem[fieldToUpdate] = o.Item2.ToString(); // o.Item2: new string for plain text multiline field
listItem.Update();
ctx.ExecuteQuery();
}
The ExecuteQuery() fails with an error "Invalid request."
Writing a single line text field with max. 255 chars this method works fine, so I assume that for multiline text fields I need to somehow handle this long strings in another way. Unfortunately I couldn't find any suitable FieldValue classes in the API.
I would appreciate any help.
What's the detailed characters for updating the multiple line text field ?
I tested the code snippet, it's working to update the field:
ClientContext ctx = new ClientContext("http://sp/sites/MyDev");
Web web = ctx.Web;
ctx.Load(web);
ctx.ExecuteQuery();
List list = web.Lists.GetByTitle("MyList");
ListItem item = list.GetItemById(1);
item["Note"] = "TestCharacter";
item.Update();
ctx.ExecuteQuery();
Jerry_MSFTs code as well as mine work fine. The issue with SharePoint Online is that requests will fail when the custom field you like to update is named "Properties". After creating a field with another name everything works smoothly.

Add FileName in ListView

Consider that in Folder xxx I have 3 files and I want to return the names of those 3 file in a ListView.
My updater function runs every second, which means that the ListView items must always be updated with the new files.
How do I do this?
You can use the DirectoryInfo class.
https://msdn.microsoft.com/en-us/library/4cyf24ss(v=vs.110).aspx
You should call the GetFiles() method, which will return a list with the file names presented in the directory.

Foreach loop to extract text file, from Access datable, using columns from Excel

What I have to do is create a console application that extracts a single table, from an Access database, using an SQL query in app.config, so that it is possible to change the SQL without changing the code in the application.
The extracted information has to be in a text file format. The hard part is that I have an Excel file with the mapping of the table and I only need to extract that information, and add some other.
For example, I will need to create a new column that is not originally in the datatable and give it a default value. And that information is in the Excel file.
I already have the connections done and I extracted a table that I need from the Access database, for a temporary datatable. I already have a datatable from the Excel file with only the columns I will need to use in a temporary datatable.
I need to create a foreach loop to check if the A column in Excel is in use. If yes then I need to check another column that contains the name of that column in the Access datatable, if there is a value I need to to extract that column to the text file, if there is no value I need to check another column that contains a default value and I need to add that value to a column that doesn't exist in the database. If there are no values in both those columns than I need to just add a blank space with the width value in the text file.
All these columns extracted to the text file need to have the width-string.width has a blank space between them and there is no need to extract the column names.
This what I have so far:
static void createfile(DataTable accessTable, DataTable excelTable)
{
string strFileData = "";
foreach(DataRow accessRow in accessTable.Rows)
{
foreach (DataRow excelrow in excelTable.Rows)
{
string fieldname = "";
fieldname = excelrow["FieldName"] //if it's not empty
strFileData.insert accessRow[fieldname];
string test = accessRow[fieldname.ToString()];
if(position == 0)
strFileData = strFileData.Insert(0,iNoOf2025.ToString().PadLeft(width, '0'));
}
//insert in the text file
Thank you for your answers, i already solved the problem, I just needed to create a foreach inside a foreach and specify the operations inside each foreach loop with some if operators.

Saving a text file to a SQL database without column names

I am reading a text file in C# and trying to save it to a SQL database. I am fine except I don't want the first line, which is the names of the columns, included in the import. What's the easiest way to exclude these?
The code is like this
while (textIn.Peek() != -1)
{
string row = textIn.ReadLine();
string[] columns = row.Split(' ');
Product product = new Product();
product.Column1 = columns[0];
etc.....
product.Save();
}
thanks
If you are writing the code yourself to read in the file and then importing...why don't you just skip over the first line?
Here's my suggestion:
string[] file_rows;
using(var reader=File.OpenText(filepath))
{
file_rows=reader.ReadToEnd().Split("\r\n");
reader.Close();
}
for(var i=1;i<file_rows.Length;i++)
{
var row=file_rows[i];
var cells=row.Split("\t");
....
}
how are you importing the data? if you are looping in C# and inserting them one at a time, construct your loop to skip the first insert!
or just delete the first row inserted after they are there.
give more info, get more details...
Pass a flag into the program (in case in future the first line is also data) that causes the program to skip the first line of text.
If it's the same column names as used in the database you could also parse it to grab the column names from that instead of hard-coding them too (assuming that's what you're doing currently :)).
As a final note, if you're using a MySQL database and you have command line access, you may want to look at the LOAD DATA LOCAL INFILE syntax which lets you import pretty arbitrarily defined CSV data.
For future reference have a look at this awesome package: FileHelpers Library
I can't add links just yet but google should help, it's on sourceforge
It makes our lives here a little easier when people insist on using files as integration

Categories

Resources