所以我正在撰寫一個 C# 程式,它將多個文本檔案組合成一個并將它們保存為一個組合文本檔案。我有一個問題,我有一個文本欄位,它選擇了保存編譯的接收的預期檔案夾,但是在選擇所需的檔案夾時,它會生成檔案名到文本框,每次Follwing最終/必須洗掉檔案名。保存功能正常作業。我想知道,如何洗掉檔案目錄中最后一個 / 之前的最后一個字母之后的所有文本?
這是代碼:
private void RecieptDisplayed_TextChanged(object sender, EventArgs e)
{
try
{
string[] fileAry = Directory.GetFiles(RecieptSelect.Text);
string input = RecieptSelect.Text;
int index = input.LastIndexOf("/");
if (index >= 0)
input = input.Substring(0, index);
MessageBox.Show("Reciepts being processed : " index);
using (TextWriter tw = new StreamWriter(savefileas.Text "RecieptsCombined.txt", true))
{
foreach (string filePath in fileAry)
{
using (TextReader tr = new StreamReader(filePath))
{
tw.WriteLine("Reciept for: " " " filePath tr.ReadToEnd()) ;
tr.Close();
tr.Dispose();
}
MessageBox.Show("File Processed : " filePath);
}
tw.Close();
tw.Dispose();
}
}
uj5u.com熱心網友回復:
你有一個像
var fullpath = @"C:\temp\myfile.txt";
您可以使用:
var dir = Path.GetDirectoryName(fullpath);
要得到
c:\temp
請注意,如果路徑以斜杠結尾,則不會在“進入目錄”之前將其洗掉,因此c:\temp變為 c:\temp`。盡量讓你的路徑沒有尾部斜杠
在操作作為路徑的字串時,嘗試始終使用 Path 類。它有大量有用的方法(這不是一個詳盡的串列,而是我最常用的方法),例如:
GetFileName
GetFileNameWithoutExtension
GetExtension
ChangeExtension
Combine
最后一個構建路徑,例如:
Path.Combine("c:", "temp", "myfile.txt");
它知道它運行的不同作業系統并適當地構建路徑——如果你在 Linux 上使用 net core,它會使用它"/"而不是"\"例如。完整檔案在這里
uj5u.com熱心網友回復:
從字串構造一個FileInfo 物件,然后使用DirectoryName或Directory。
另外,不要連接字串來獲取檔案名,而是使用Path.Combine。
uj5u.com熱心網友回復:
您正在從給定路徑中查找目錄名稱,您可以使用現有函式來獲取目錄名稱, Path.GetDirectoryName()
using System.IO;
...
//Get the directory name
var directoryName = Path.GetDirectoryName(savefileas.Text);
using (TextWriter tw = new StreamWriter(Path.Combine(directoryName, "RecieptsCombined.txt"), true))
{
foreach (string filePath in fileAry)
{
using (TextReader tr = new StreamReader(filePath))
{
tw.WriteLine("Reciept for: " " " filePath tr.ReadToEnd()) ;
tr.Close();
tr.Dispose();
}
MessageBox.Show("File Processed : " filePath);
}
tw.Close();
tw.Dispose();
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/337499.html
上一篇:如何快速將大量資料轉換為字串?
