Sharepoint SPFile - Get File Type - c#

I am using SPFile to display a list of files and I want to display the type of file, as a string, so PDF, Word, Excel etc.
Looks like:
FileABC PDF
FileDEF Excel
I have got the icon back using "ListItem.File.IconUrl", ListItem is SPListItem
But I would like to get the file type as a name. It must work out the file type so the correct image can be displayed but I want to display the words too (for accessibility)

You can simply take the "FileLeafRef" attribute which contains filename + local path, create an System.IO.FileInfo object out of that and then access the .Extension property:
System.IO.FileInfo inf = new System.IO.FileInfo("/images/files/something.gif");
Console.WriteLine(inf.Extension); //outputs .gif
I believe it will not be that easy to find matching program for each extension (you mention you need "Excel" not "xls". So, the easiest way, i think, is to create a dictionary of known extensions. Something like this:
System.Collections.Specialized.StringDictionary oDict = new System.Collections.Specialized.StringDictionary();
oDict.Add(".xls", "Excel");
oDict.Add(".xlsx", "Excel");
oDict.Add(".doc", "Word");
and then:
oDict[inf.Extension]

You can get the extension from the listitem as
ListItem[SPBuiltInFieldId.DocIcon]

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

Read file to inmemory user manipulates info, then overwrites data back to same file in C#

I have been reading posts trying to figure how to get this done. The title says it all. I am trying to take simple data from a text file and load in memory. Then let the user manipulate (add/delete) data in memory and have it added to an List<Automobile>. Then have it write what is in memory back to the same file by overwriting what is there. I have tried to use different parts of MemoryStream() and trying to use StreamReader(). I would get an error saying "Argument 1: cannot convert from 'string' to 'Exercise6_DealerVehicleInventory.Automobile'". When I would use MemoryStream, it would give me an error saying "Cannot implicitly convert type 'System.IO.StreamReader' to 'string'"
I am not that familiar with the .net framework and what all can be done with. What is the best way to go about doing what the Title of my post says? I have been reading for the past few days and not been able to figure this out. I am still very new to all that C# has to offer when writing applications.
PS: Where it says "Exercise6", this is not for school by any means. This is something that I was given and told to use online for help/answers if I had issues.
If there is another post that explains all of this, please point me to that post because I have not found a post/answer to what I am trying to get done.
C# makes this very easy for you.
string content = System.IO.File.ReadAllText("filename.txt");
// change content here
System.IO.File.WriteAllText("filename.txt", content);
To simplify things, you should add using System.IO; to the top of your file, and then you don't have to include System.IO in the body of the code.
I assume that:
Each line in the input file represents a single automobile.
You want to convert this list of strings to list of automobiles.
For simplicity, let's define the class Automobile as follows:
public class Automobile
{
public string Name;
//you can add more fields here.
}
Let's say that your input file "automobiles.txt" has the following lines:
auto1
auto2
auto3
Your program should be:
// read file content
string sFilePath = #"C:\Users\user\Desktop\automobiles.txt";
string[] aLines = File.ReadAllLines(sFilePath);
// initialize an empty list of automobiles
List<Automobile> lAutomobiles = new List<Automobile>();
// initialize a list of automobiles from file content
aLines.ToList().ForEach(line => lAutomobiles.Add(new Automobile { Name = line }));
// here, do whatever you want with the automobiles list
lAutomobiles.ForEach(auto => auto.Name += "_processed");
// write the processed data to the file
File.WriteAllLines(sFilePath, lAutomobiles.Select(auto => auto.Name));
After running this code, the lines in automobiles.txt are:
auto1_processed
auto2_processed
auto3_processed
The error says that you want to add a string value to a list of Autmobile type.so you should create a complete Autombile class that has all info about autombiles, then when add to the list you can write something like that:
List<Autombile> auto = new List<Autombile>();
auto.Add(new Autombile() { Name = "user's auto name", Model = "user's auto model" });

Conditional file listing on gridView in ASP.NET?

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.

How to get all files from a folder in sorted order in C#.Net? [duplicate]

Is is possible to get files that is ordered same as in Windows Explorer
I know "natural sort", but it's not what I need, I need to get the file list ordered by the same attribute in Windows Explorer, for example:
If I ordered a directory by the attribute "create date", then I will get a file list as below:
name create date file size
1.txt 2012/1/1 125Kb
2.tab 2012/3/2 15Kb
3.bmp 2013/5/5 26Kb
If my windows explorer order file list with the attribute "file size", the the file list would be:
name create date file size
2.tab 2012/3/2 15Kb
3.bmp 2013/5/5 26Kb
1.txt 2012/1/1 125Kb
Could anyone help?
I think this is going to be a lot more complex than you expect. Folder settings are stored in the registry in two places:
HKCU\Software\Microsoft\Windows\Shell\BagMRU
HKCU\Software\Microsoft\Windows\Shell\Bags
The first path contains a structure which reflects the structure of the file system, and the second path contains details about those items, including a REG_BINARY value called "Sort" which records the sort order used for that folder.
See Willi Balenthin's website for details on the structure, including sample code (in Python)
Here's how to get a list of files sorted by their name:
var path = #"C:\windows"; // obviously change this to whatever you want
var files = System.IO.Directory.GetFiles (path).ToList ();
file.Sort();
And that's it!
Here's how you would do it per your given code sample:
var temperaturePressureSignalFilesList = Directory.GetFiles(TemperaturePressureSignalDirectory, "*.txt", SearchOption.TopDirectoryOnly).ToList();
temperaturePressureSignalFilesList.Sort();
using System.Linq;
DirectoryInfo info = new DirectoryInfo(""); FileInfo[] files =
info.GetFiles().OrderBy(p => p.CreationTime).ToArray(); foreach
(FileInfo file in files) {
// DO Something... }
here is the sample code for get files in directory by creation time.
You can get files by size same way.
I guess you are talking about viewing pane in Windows Explorer (it's essentially a Windows File Manager but also known under different name). Some clarification is needed. You can apply your custom sorting on various columns; moreover, you can have multiple viewing panes (windows) open sorted on different columns. Thus, the problem definition is a bit unclear.
Assuming that you know the sorting order in your viewing panes, then you can use System.IO.DirectoryInfo and derived FileSystemInfo[] objects; the latter has files.OrderBy method.
Hope this will help. My best, Alex
If you want natural sort order, you should either P/Invoke StrCmpLogicalW (http://msdn.microsoft.com/en-us/library/bb759947.aspx) or find a managed natural sort algorithm. There is no built-in natural sort in .NET Framework.
I think you cannot know which is the order in the pane (by size, name or whatever), you must read the list and then sort it the way you want or prompt the user to select a sorting attribute.
As Kenny posted Sorting Directory.GetFiles() here is an approach, anyway I still thinking there is no possibly way to know which is the sorting order that user selected in the viewing pane.
I think you would have to write a shell extension for windows explorer that captures sort events on columns and writes that metadata to disk in some structured way. You may have multiple explorer windows open so might be an idea to apply timestamp or id so you know which explorer window you are dealing with. Then in your app read that metadata to get the sort order and apply accordingly. Not easy but doable.

Copy Word document Userform to another

I have this code below to copy VBA codes from one word document to another (I'm using C#). It works for modules however I can't seem to get it to work with userforms.
VBComponent sourceVBC = GetSourceDocVB();
VBComponent targetVBC = document.VBProject.VBComponents.Add(sourceVBC.Type);
string codes = sourceVBC.CodeModule.get_Lines(1, sourceVBC.CodeModule.CountOfLines);
targetVBC.CodeModule.AddFromString(codes);
targetVBC.Name = sourceVBC.Name;
Yes, the userform is copied to the target document but its fields are not. Like if it contains labels and textboxes. Those fields are not copied. Am I missing something here?
Yes, you are missing something. Forms are not defined in the code file only, but need a binary file too.
You don't tell anything about the way the source files are generated. Normally, in VBA, you use the "Export" statement of the VBComponent object. Of course one can do it manually by going to the VBA Editor in Word, right-clicks the project component and selects "Export". If you have a look into the export folder, you'll see that a form is saved as two files "Form1.frm" (containing the code) and "Form1.frx" (containing binary form data, as labels and other stuff).
In the other project, you can use maually the File, Import function, which takes care of the binary definition if you import a form.
In VBA, you may use something like this to export from a project:
For Each vbC In ActiveDocument.VBProject.VBComponents
Select Case vbC.Type
Case vbext_ct_StdModule
strVbcExt = ".bas"
Case vbext_ct_ClassModule
strVbcExt = ".cls"
Case vbext_ct_MSForm
strVbcExt = ".frm"
Case Else
End Select
strvbCName = vbC.Name
strFilename = strPath & "\" & strvbCName & strVbcExt
vbC.Export strFilename
(omitted the rest)
And to import you'll use
ActiveDocument.VBProject.VBComponents.Import strFilename

Categories

Resources