Creating hierarchy of folders - c#

So I am converting an mp3 into wav, using NAudio
Example
string InputAudioFilePath = #"C:\Users\sdkca\Desktop\song.mp3";
string OutputAudioFilePath = #"C:\Users\sdkca\Desktop\song_converted.wav";
using (Mp3FileReader reader = new Mp3FileReader(InputAudioFilePath, wf => new Mp3FrameDecompressor(wf)))
{
WaveFileWriter.CreateWaveFile(OutputAudioFilePath, reader);
}
So in my view model, I am doing the following
I am getting the Documents folder
private static readonly string DocumentsPath = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
Then I am doing this
const string ext = ".wav";
var dlg = new OpenFileDialog
{
Filter = Constants.FILEFILTER
};
var res = dlg.ShowDialog();
if (res! == true)
{
var AudioName = Path.GetFileNameWithoutExtension(dlg.FileName);
var FoderParent = Path.Combine(DocumentsPath, Constants.TRANSCRIPTIONS);
var ParentSubFolder = Path.Combine(FoderParent, Constants.AUDIO);
var filename = Path.Combine(ParentSubFolder, $"{AudioName}{ext}");
using var mp3 = new Mp3FileReader(dlg.FileName);
using var ws = WaveFormatConversionStream.CreatePcmStream(mp3);
WaveFileWriter.CreateWaveFile(filename, ws);
}
I am getting this error
System.IO.DirectoryNotFoundException: 'Could not find a part of the path 'C:\Users\egome\OneDrive - Universidad Politécnica de Madrid\Documents\Transcriptions\Audio\10.wav'.'
What I do not understand is, that I am doing a combine between my folder and a new fileName.wav, that is required by the method

Add this check before creating filename string
if(!Directory.Exists(ParentSubFolder))
Directory.CreateDirectory(ParentSubFolder);
var filename = Path.Combine(ParentSubFolder, $"{AudioName}{ext}");
This way, you make sure all path parts exist.

Related

Could not find a part of path - ASP.NET Core

I can not upload any file today!
I said "today" because it was working yesterday. I did not change anything that might be related to that.
I always get this error:
Could not find a part of the path
It is worth mentioning that every configuration is declared in program file.
My Uploader method:
public string Upload(IFormFile? file, string path, string fileToRemove = "")
{
if (file == null)
return "";
var directoryPath = $"{_webHostEnvironment.WebRootPath}/{path}";
if (!Directory.Exists(directoryPath))
Directory.CreateDirectory(directoryPath);
var fileName = $"{DateTime.Now.ToFileTime()}-{file.FileName}";
var filePath = $"{directoryPath}/{fileName}";
using var stream = File.Create(filePath);
file.CopyTo(stream);
if (!string.IsNullOrEmpty(fileToRemove) ||
!string.IsNullOrWhiteSpace(fileToRemove))
{
var fileToRemovePath = $"{_webHostEnvironment.WebRootPath}/{fileToRemove}";
if (File.Exists(fileToRemovePath))
File.Delete(fileToRemovePath);
}
return $"{path}/{fileName}";
}

How to open only a .dat file. In C#

I'm trying to open a file but I want it filter out to only .dat file.
using (OpenFileDialog fileChooser = new OpenFileDialog())
{
result = fileChooser.ShowDialog();
fileName = fileChooser.FileName; //Get file name.
fileChooser.Filter = "Data File|*.dat;";
fileChooser.DefaultExt = "dat";
fileChooser.AddExtension = true;
}
When having a OpenFileDialog in "using" the filter, defaultExt and Addextension doesn't work.
You should set filters before the call of "ShowDialog" method.
This should work.
using (var fileChooser = new OpenFileDialog())
{
// define the filters (first description | first filter; second description ...
fileChooser.Filter = "Data File|*.dat";
// select the first filter
fileChooser.FilterIndex = 1;
fileChooser.DefaultExt = "dat";
fileChooser.AddExtension = true;
// show the Opendialog
if (fileChooser.ShowDialog() == DialogResult.OK)
{
// get the path of specified file
var filename = fileChooser.FileName;
// use the filename to open the file...
}
}

How to get all the files form a directory where name does not contains 0?

Recently I have built a small converter that converts txt data to xml in a certain structure , I choose a folder and the program loops through all the files in that folder and write in a XML format all together in one xml document.
In the folder I have data names like:
Data.0001.txt
Data.0002.txt
Data.0003.txt
Data.0004.txt
Data.txt
and so on
I want only the files that dose NOT contain zeros in them because ones with zeros are just a back up copy for the others , and i have over 6000 file i can't filter them manually
Here is my code so far
static void Main(string[] args)
{
FolderBrowserDialog SelectFolder = new FolderBrowserDialog();
String path = #"C:\newpages";
XmlDocument doc = new XmlDocument();
XmlElement root = doc.CreateElement("Pages");
if (SelectFolder.ShowDialog() == DialogResult.OK)
{
var txt = string.Empty;
string[] Files = Directory.GetFiles((SelectFolder.SelectedPath));
int i = 1;
foreach (string path1 in Files)
{
String filename = Path.GetFileNameWithoutExtension((path1));
using (StreamReader sr = new StreamReader(path1))
{
txt = sr.ReadToEnd();
XmlElement id = doc.CreateElement("Page.id");
id.SetAttribute("Page.Nr", i.ToString());
id.SetAttribute("Pagetitle", filename);
XmlElement name = doc.CreateElement("PageContent");
XmlCDataSection cdata = doc.CreateCDataSection(txt);
name.AppendChild(cdata);
id.AppendChild(name); // page id appenndchild
root.AppendChild(id); // roots appenedchild
doc.AppendChild(root); //Main root
}
i++;
}
}
Console.WriteLine("finished");
Console.ReadKey();
doc.Save(Path.ChangeExtension(path, ".xml"));
}
}
Any help would be really nice guys
GetFiles returns the name of a file in a specified directory. Its return type is string[] so you can easily apply a Where to filter the file names as follow:-
var files = Directory.GetFiles("PathToYourDirec").Where(name => !name.Contains("0"));
On the string filename you could make sure it doesn't contain "0"
if(!filename.Contains("0"))
{
}
On the Files variable you can use a regex to filter out the filenames which contains only letters
var reg = new Regex(#"^([^0-9]*)$");
var files = Directory.GetFiles("path-to-folder")
.Where(path => reg.IsMatch(path))
.ToList();
The whole code can be largely simplified while solving this issue. You don't need a StreamReader just to read the whole file, and you may as well get the filename early and filter instead of going into the foreach and filtering :
static void Main(string[] args)
{
FolderBrowserDialog SelectFolder = new FolderBrowserDialog();
String path = #"C:\newpages";
XmlDocument doc = new XmlDocument();
XmlElement root = doc.CreateElement("Pages");
if (SelectFolder.ShowDialog() == DialogResult.OK)
{
// Don't declare txt here, you're overwriting and only using it in a nested loop, declare it as you use it there
// var txt = string.Empty;
//string[] Files = Directory.GetFiles((SelectFolder.SelectedPath));
// Change to getting FileInfos
var Files = new DirectoryInfo(SelectFolder.SelectedPath).GetFiles()
// Only keep those who don't contain a zero in file name
.Where(f=>!f.Name.Contains("0"));
int i = 1;
foreach (var file in Files)
{
//String filename = Path.GetFileNameWithoutExtension((path1));
// Don't need a StreamReader not a using block, just read the whole file at once with File.ReadAllText
//using (StreamReader sr = new StreamReader(path1))
//{
//txt = sr.ReadToEnd();
var txt = File.ReadAllText(file.FullName);
XmlElement id = doc.CreateElement("Page.id");
id.SetAttribute("Page.Nr", i.ToString());
id.SetAttribute("Pagetitle", file.FullName);
XmlElement name = doc.CreateElement("PageContent");
XmlCDataSection cdata = doc.CreateCDataSection(txt);
name.AppendChild(cdata);
id.AppendChild(name); // page id appenndchild
root.AppendChild(id); // roots appenedchild
doc.AppendChild(root); //Main root
//}
i++;
}
}
Console.WriteLine("finished");
Console.ReadKey();
doc.Save(Path.ChangeExtension(path, ".xml"));
}
I would also advise not working with the XML api you're using but with the more recent and simpler linq to XML one as that would simplify creating your elements too, see bellow a very simplified version of the whole code as i'd have writen it with LINQ and XElements
static void Main(string[] args)
{
FolderBrowserDialog SelectFolder = new FolderBrowserDialog();
String path = #"C:\newpages";
var root = new XElement("Pages");
if (SelectFolder.ShowDialog() == DialogResult.OK)
{
var FilesXML = new DirectoryInfo(SelectFolder.SelectedPath).GetFiles()
.Where(f => !f.Name.Contains("0"))
// Note that the index is 0 based, if you want to start with 1 just replace index by index+1 in Page.Nr
.Select((file, index) =>
new XElement("Page.id",
new XAttribute("Page.Nr",index),
new XAttribute("Pagetitle",file.FullName),
new XElement("PageContent",
new XCData(File.ReadAllText(file.FullName))
)));
// Here we already have all your XML ready, just need to add it to the root
root.Add(FilesXML);
}
Console.WriteLine("finished");
Console.ReadKey();
root.Save(Path.ChangeExtension(path, ".xml"));
}
You can try this, but I would suggest if you change the logic of creating name of backup files. It should not depend on "0" as character in it but instead of that firm text like "backup" should be mentioned in file name.
static void Main(string[] args)
{
FolderBrowserDialog SelectFolder = new FolderBrowserDialog();
String path = #"C:\newpages";
XmlDocument doc = new XmlDocument();
XmlElement root = doc.CreateElement("Pages");
if (SelectFolder.ShowDialog() == DialogResult.OK)
{
var txt = string.Empty;
string[] Files = Directory.GetFiles((SelectFolder.SelectedPath));
int i = 1;
foreach (string path1 in Files)
{
String filename = Path.GetFileNameWithoutExtension((path1));
if (!filename.Contains(".0"))
{
using (StreamReader sr = new StreamReader(path1))
{
txt = sr.ReadToEnd();
XmlElement id = doc.CreateElement("Page.id");
id.SetAttribute("Page.Nr", i.ToString());
id.SetAttribute("Pagetitle", filename);
XmlElement name = doc.CreateElement("PageContent");
XmlCDataSection cdata = doc.CreateCDataSection(txt);
name.AppendChild(cdata);
id.AppendChild(name); // page id appenndchild
root.AppendChild(id); // roots appenedchild
doc.AppendChild(root); //Main root
}
}
i++;
}
}
Console.WriteLine("finished");
Console.ReadKey();
doc.Save(Path.ChangeExtension(path, ".xml"));
}

Get Original file name in file sharing Xamarin.forms

I'm trying to implement the file sharing from other apps in Xamarin.Forms.
And I have some issues with Android implementation.
I'm referring to code of https://codemilltech.com/sending-files-to-a-xamarin-forms-app-part-2-android/.
if (Intent.Action == Intent.ActionSend)
{
var uriFromExtras = Intent.GetParcelableExtra(Intent.ExtraStream) as Android.Net.Uri;
string path = Intent.GetParcelableExtra(Intent.ExtraStream).ToString();
var subject = Intent.GetStringExtra(Intent.ExtraSubject);
// Get the info from ClipData
var pdf = Intent.ClipData.GetItemAt(0);
// Open a stream from the URI
var pdfStream = ContentResolver.OpenInputStream(pdf.Uri);
// Save it over
var memOfPdf = new System.IO.MemoryStream();
pdfStream.CopyTo(memOfPdf);
var docsPath = System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal);
var filePath = System.IO.Path.Combine(docsPath, "temp");
System.IO.File.WriteAllBytes(filePath, memOfPdf.ToArray());
mainForms.ShareFile(memOfPdf.ToArray(), System.IO.Path.GetFileName(path));
}
And I need to get the original name of shared file from File Manager.
Can anyone help me?
Here is a solution that gets the original file name of a shared file through an intent.
if (Intent.Action == Intent.ActionSend)
{
ClipData clip = Intent.ClipData;
Uri uri = clip.GetItemAt(0).Uri;
ICursor returnCursor = ContentResolver.Query(uri, null, null, null, null);
int nameIndex = returnCursor.GetColumnIndex(IOpenableColumns.DisplayName);
returnCursor.MoveToFirst();
var fileName = returnCursor.GetString(nameIndex);
Toast.MakeText(this,"fileName == " + fileName, ToastLength.Short).Show();
}
Examples: .png file and an xls file.

Loading tsv/csv file in excel sheet

This is my code.
public static string LoadPackage(DirectoryInfo outputDir, string name)
{
FileInfo newFile = new FileInfo(outputDir.FullName + #"\test.xlsx");
if (newFile.Exists)
{
newFile.Delete();
newFile = new FileInfo(outputDir.FullName + #"\test.xlsx");
}
var format = new ExcelTextFormat();
format.Delimiter = '\t';
format.SkipLinesBeginning = 1;
using (ExcelPackage package = new ExcelPackage())
{
LoadSheet(package, outputDir, name);
package.SaveAs(newFile);
}
return newFile.FullName;
}
And after that i call LoadSheet method in order to fill my excel file from tsv file.
public static void LoadSheet(ExcelPackage package, DirectoryInfo
outputDir, string name)
{
var ws = package.Workbook.Worksheets.Add("Content");
var format = new ExcelTextFormat();
format.Delimiter = '\t';
format.SkipLinesBeginning = 2;
format.SkipLinesEnd = 1;
var range = ws.Cells["A1"].LoadFromText(new
FileInfo(outputDir.FullName + "\\" + name), format,
TableStyles.Medium27, false);
}
And this is my code on button click event
if (BrowseFileUpload.HasFile)
{
var name = BrowseFileUpload.PostedFile.FileName;
InputTextBox.Text = name;
LoadData.LoadPackage(new
System.IO.DirectoryInfo("C:\\Users\\Nemanja\\Downloads"), name);
InfoLabel.Text = "Your data has been imported!!!";
InfoLabel.ForeColor = System.Drawing.Color.Blue;
InfoLabel.Font.Size = 20;
}
Everything is ok i create new excel file, sheet save it but it does not load data that i need it to load inside excel file. It's only empty file or i get a error the file is corrupted recover what you can.
Can someone figure out what can be a problem based on my explanation and this code. Thank you all good people.
I think that the problem may well be with the format of your source data. I've put together the following sample, based on your code, and it works fine.
var outFile = Path.ChangeExtension(filePath, ".xlsx");
using (var p = new ExcelPackage())
{
var fmt = new ExcelTextFormat();
fmt.Delimiter = '\t';
fmt.SkipLinesBeginning = 2;
fmt.SkipLinesEnd = 1;
fmt.EOL = ((char)10).ToString(); // THIS LINE FIXED THE PROBLEM (UNIX NEWLINE)
var ws = p.Workbook.Worksheets.Add("Imported Text");
ws.Cells[1, 1].LoadFromText(new FileInfo(filePath), fmt, TableStyles.Medium27, false);
p.SaveAs(new FileInfo(outFile));
}
Try running your data through this and see if you get the same issue or not.
UPDATED
The problem was a unix-style newline in the file - EPPlus expects a windows-style newline by default

Categories

Resources