using System.Text;
using System.Runtime.InteropServices;
/// <summary>
/// freeware helper class for using INI-files
/// (W) 2012 by admin of codezentrale.de
///
/// usage:
///
/// IniFile _ini = new IniFile("c:\\testini.ini");
/// if (_ini != null)
/// {
/// string r = _ini.IniReadValue("section", "key", "default");
///
/// if (_ini.IniWriteValue("section", "key", "value"))
/// {
/// ...
/// }
/// }
/// </summary>
public class IniFile
{
private string _INIfile = string.Empty;
[DllImport("kernel32.dll", EntryPoint = "WritePrivateProfileStringW", CharSet = CharSet.Unicode, SetLastError = true, ExactSpelling = true, CallingConvention = CallingConvention.StdCall)]
[return: MarshalAs(UnmanagedType.Bool)]
private static extern bool WritePrivateProfileString(string lpAppName, string lpKeyName, string lpString, string lpFileName);
[DllImport("kernel32.dll", EntryPoint = "GetPrivateProfileStringW", CharSet = CharSet.Unicode, SetLastError = true, ExactSpelling = true, CallingConvention = CallingConvention.StdCall)]
private static extern int GetPrivateProfileString(string lpAppName, string lpKeyName, string lpDefault, StringBuilder lpReturnedString, uint nSize, string lpFileName);
/// <summary>
/// current INI-file
/// </summary>
public string IniFileName
{
get { return _INIfile; }
}
/// <summary>
/// INIFile constructor
/// </summary>
/// <PARAM name="INIPath">INI file</PARAM>
public IniFile(string INIfile)
{
_INIfile = INIfile;
}
/// <summary>
/// write data to the INI-file
/// </summary>
/// <param name="section">Section name</PARAM>
/// <param name="key">Key Name</PARAM>
/// <param name="value">Value Name</PARAM>
/// <returns>true if success</returns>
public bool IniWriteValue(string section, string key, string val)
{
return WritePrivateProfileString(section, key, val, _INIfile);
}
/// <summary>
/// read data value from the INI-file
/// </summary>
/// <param name="section"section name</PARAM>
/// <param name="key">key name</PARAM>
/// <param name="def">default value on error</param>
/// <returns>Value or def on error</returns>
public string IniReadValue(string section, string key, string def)
{
StringBuilder sb = new StringBuilder(255);
int iCharsRead = GetPrivateProfileString(section, key, def, sb, (uint)sb.Capacity, _INIfile);
return sb.ToString();
}
}
Kategorie: Filesystem
Testen, ob ein Dateiname bestimmte (unerlaubte) Zeichen beinhaltet
string sFileName = "abc.txt";
if (sFileName.IndexOfAny(Path.GetInvalidFileNameChars()) -> -1)
{
// sFileName beinhaltet unerlaubte Zeichen
}
Mehrfachfilter auf Directory.GetFiles() anwenden
// Aufruf:
//
// string[] saFilterList = { "*.csv", "*.txt" };
// List<string-> lFileList = this.GetFilesByFilter(@"c:\temp\", saFilterList);
//
// foreach (string f in lFileList)
// {
// ...
// }
//
using System.IO;
/// <summary>
/// listet Dateien eines Verzeichnisses anhand eines übergebenen Filters
/// </summary>
/// <param name="sPath">Suchpfad</param>
/// <param name="saFilterList">Filterliste (*.csv, *.txt)</param>
/// <returns>Dateiliste</returns>
public List<string-> GetFilesByFilter(string sPath, string[] saFilterList)
{
List<string-> lFileList = new List<string->();
if (Directory.Exists(sPath))
{
foreach (string filter in saFilterList)
{
lFileList.AddRange(Directory.GetFiles(sPath, filter));
}
}
return lFileList;
}
[C#] CSV-Daten in DataTable einlesen und in DataGridView anzeigen
// dgvGrid == DataGridView auf dem Formular
private void btnOpen_Click(object sender, EventArgs e)
{
// Datei öffnen
if (openFileDialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
// DataTable hält die gesplitteten CSV-Daten
DataTable dt = new DataTable();
// Datei öffnen, hier als UTF8
using (StreamReader sr = new StreamReader(openFileDialog.FileName, Encoding.UTF8))
{
// bis Dateiende lesen
while (!sr.EndOfStream)
{
// Zeile einlesen und anhand des Trennzeichens ";" in einzelne Spalten (stringarray) splitten
string[] currentline = sr.ReadLine().Split(new string[] { ";" }, StringSplitOptions.None);
// wenn neue Tabelle (noch keine Spalten enthalten)
if (dt.Columns.Count == 0)
{
// n Spalten der ersten gelesenen Zeile hinzufügen
for (int i = 0; i < currentline.Length; i++)
{
// als Spaltenüberschrift die eingelesenen Teile des Stringarrays verwenden
dt.Columns.Add(currentline[i]);
}
}
else
{
// ansonsten Daten des Stringarrays zeilenweise hinzufügen
dt.Rows.Add(currentline);
}
}
// Stream schließen
sr.Close();
}
// DataTable an das Gitter auf der Oberfläche übergeben und somit anzeigen
dgvGrid.DataSource = dt;
}
}
TrailingPathDelimiter für Pfadnamen hinzufügen oder entfernen
using System.IO;
/// <summary>
/// freeware helper class for managing DirectorySeparatorChar
/// (W) 2011 by admin of codezentrale.de
/// </summary>
public static class FileSystem
{
/// <summary>
/// include ending DirectorySeparatorChar
/// </summary>
/// <param name="path">current path</param>
/// <returns>path with ending DirectorySeparatorChar</returns>
public static string IncludeTrailingPathDelimiter(string path)
{
return path.EndsWith(Path.DirectorySeparatorChar.ToString()) ? path : path + Path.DirectorySeparatorChar;
}
/// <summary>
/// exclude ending DirectorySeparatorChar
/// </summary>
/// <param name="path">current path</param>
/// <returns>path without ending DirectorySeparatorChar</returns>
public static string ExcludeTrailingPathDelimiter(string path)
{
return path.EndsWith(Path.DirectorySeparatorChar.ToString()) ? path.Remove(path.Length, 1) : path;
}
}
FileAttribute lesen und setzen
string sFile = @"c:\Test.txt";
// FileAttribute lesen
FileAttributes fa = File.GetAttributes(sFile);
// FileAttribute testen
// Archive
if ((fa & FileAttributes.Archive) == FileAttributes.Archive)
{
}
// ReadOnly
if ((fa & FileAttributes.ReadOnly) == FileAttributes.ReadOnly)
{
}
// Hidden
if ((fa & FileAttributes.Hidden) == FileAttributes.Hidden)
{
}
// System
if ((fa & FileAttributes.System) == FileAttributes.System)
{
}
// FileAttribute zusätzlich anschalten
// Archive und ReadOnly zu den schon gesetzten anschalten
File.SetAttributes(sFile, fa | (FileAttributes.Archive | FileAttributes.ReadOnly));
// FileAttribute ausschließlich setzen
// nur Archive und ReadOnly anschalten
File.SetAttributes(sFile, FileAttributes.Archive | FileAttributes.ReadOnly);
// FileAttribute löschen
// alle löschen, auf Normal setzen
File.SetAttributes(sFile, FileAttributes.Normal);
// Archive und ReadOnly löschen
File.SetAttributes(sFile, fa & ~(FileAttributes.Archive | FileAttributes.ReadOnly));
Verzeichnis erstellen
using System.IO;
Directory.CreateDirectory("C:\\Temp\\SubDir");
Streams asynchron lesen und schreiben
Eine schöne Klasse zum asynchronen Lesen und Schreiben von Streams (Start, Stop, Pause) findet man hier: Link
Dateien blockweise mit Fortschrittanzeige kopieren
using System.IO;
// sShortFileName - Dateiname ohne Pfad
// sSourceDir - Quellpfad, dort, wo die Datei herstammt
// sDestDir - Zielpfad, dort, wo die Datei hin kopiert werden soll
private bool CopyFile(string sShortFileName, string sSourceDir, string sDestDir)
{
bool bRetVal = false;
int iBlockSize = 1048576; // Standard: 1MB Blockgröße
FileMode fmMode = FileMode.CreateNew;
try
{
if (File.Exists(sDestDir + sShortFileName))
{
if (MessageBox.Show("Datei existiert, überschreiben?", "Frage", MessageBoxButtons.YesNo) == DialogResult.Yes)
{
fmMode = FileMode.Create;
}
}
// Dateigröße holen
FileInfo fi = new FileInfo(sSourceDir + sShortFileName);
// bei kleinen Dateien die Blockgröße herabsetzen
if (fi.Length < iBlockSize) iBlockSize = (int)fi.Length;
BinaryReader brRead = new BinaryReader(new FileStream(sSourceDir + sShortFileName, FileMode.Open));
// wenn die Datei nicht überschrieben werden soll (fmMode = FileMode.CreateNew)
// wird hier eine Exception geworfen, das kopieren bricht selbsständig ab
BinaryWriter brWrite = new BinaryWriter(new FileStream(sDestDir + sShortFileName, fmMode));
int iLength = (int)(fi.Length / iBlockSize);
int iRest = (int)(fi.Length % iBlockSize);
// tspbProgress ist eine ToolStripProgressbar
tspbProgress.Value = 0;
tspbProgress.Minimum = 0;
tspbProgress.Maximum = (iRest == 0) ? iLength : iLength + 1;
// 1MB-Blöcke kopieren
for (int s = 0; s < iLength; s++)
{
brWrite.Write(brRead.ReadBytes(iBlockSize));
tspbProgress.Value++;
Application.DoEvents();
}
// den Rest (< 1MB) nachkopieren
if (iRest > 0)
{
brWrite.Write(brRead.ReadBytes(iRest));
tspbProgress.Value++;
Application.DoEvents();
}
brRead.Close();
brWrite.Close();
bRetVal = true;
}
catch (Exception e)
{
Console.WriteLine(e.Message);
Console.WriteLine(e.StackTrace);
}
return bRetVal;
}
Clustergröße eines Laufwerks herausfinden
using System.Runtime.InteropServices;
// per PInvoke aus der kernel32.dll die Funktion GetDiskFreeSpace() importieren
[DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Auto)]
static extern bool GetDiskFreeSpace(
string sRootPathName,
ref uint uiSectorsPerCluster,
ref uint uiBytesPerSector,
ref uint uiNumberOfFreeClusters,
ref uint uiTotalNumberOfClusters);
// Hilfsfunktion zum Ermitteln der Clustergröße
// theoretisch kann damit auch die Anzahl der freien Bytes
// eines LW berechnet werden (uiNumberOfFreeClusters * uiSectorsPerCluster * uiBytesPerSector)
// Problem ist hier, dass dies nur für Volumengrößen bis 2GB funktioniert
// alternativ sollte dazu dann System.IO.DriveInfo verwendet werden :)
public uint ClusterSizeInBytes(string sRootPath)
{
uint uiRetVal = 0;
uint uiSectorsPerCluster = 0;
uint uiBytesPerSector = 0;
uint uiNumberOfFreeClusters = 0;
uint uiTotalNumberOfClusters = 0;
if (GetDiskFreeSpace(sRootPath, ref uiSectorsPerCluster, ref uiBytesPerSector, ref uiNumberOfFreeClusters, ref uiTotalNumberOfClusters))
{
uiRetVal = uiSectorsPerCluster * uiBytesPerSector;
}
return uiRetVal;
}