Matlab: check if string has a correct file path syntax - matlab

I want to check if a string represents a full path of a file, like this:
p = 'C:\my\custom\path.txt'
The file does not exist, so commands like isdir and exist return false to me, but still the format of the string represents a valid path for my operating system, while the following one does not because it has an invalid character for the file name:
p = 'C:\my\custom\:path.txt'
So I'd like to know how to check if a string represents a valid file path without needing that the file actually exists.

You might want to use the regexp function with a regular expression to match Windows paths.
if isempty(regexp(p, '^(?:[a-zA-Z]\:|\\\\[\w\.]+\\[\w.$]+)\\(?:[\w]+\\)*\w([\w.])+$', 'once'))
// This is not a path
end

You can also let Matlab try for you:
if ~isdir(p)
[status, msg] = mkdir(p);
if status
isdir(p)
rmdir(p)
else
error(msg)
end
end
First, you check if the folder exists, if not you try to create it. If you succeed then you delete it, and if not you throw an error.
This is not recommended for checking many strings but has the advantage of being cross-platform.

function bool = isLegalPath(str)
bool = true;
try
java.io.File(str).toPath;
catch
bool = false;
end
end

Related

How to make the platform independent filepath slash "/" with GLib? (GJS)

I have a folderPath which has a directory string:
/home/bastian/Pictures
and I have a variable fileName which contains the name.
I can concatenate the two strings together like this, but it only works on UNIX systems:
let filePath = folderPath + '/' + fileName;
Is there a way with GLib I can concatenate the two to each other without making assumptions about the slash or backslash (to stay fx Windows-compatible)?
With help from guadec, I found out I could use GLib's g_build_filenamev () function.
let filePath = GLib.build_filenamev([folderPath, fileName]);
This builds a path to the file and respects the platform at the same time.
Note: it requires that you import GLib first at the top of your GJS file, like this:
const { GLib } = imports.gi;
If you happen to be using a Gio.File object to manipulate the path, you can also do something like this:
const folder = Gio.File.new_for_path(folderPath);
const file = folder.get_child(fileName);

How to cut a string from the end in UIPATH

I have this string: "C:\Procesos\rrhh\CorteDocumentos\Cortados\10001662-1_20060301_29_1_20190301.pdf" and im trying to get this part : "20190301". The problem is the lenght is not always the same. It would be:
"9001662-1_20060301_4_1_20190301".
I've tried this: item.ToString.Substring(66,8), but it doesn't work sometimes.
What can I do?.
This is a code example of what I said in my comment.
Sub Main()
Dim strFileName As String = ""
Dim di As New DirectoryInfo("C:\Users\Maniac\Desktop\test")
Dim aryFi As FileInfo() = di.GetFiles("*.pdf")
Dim fi As FileInfo
For Each fi In aryFi
Dim arrname() As String
arrname = Split(Path.GetFileNameWithoutExtension(fi.Name), "_")
strFileName = arrname(arrname.Count - 1)
Console.WriteLine(strFileName)
Next
End Sub
You could achieve this using a simple regular expressions, which has the added benefit of including pattern validation.
If you need to get exactly eight numbers from the end of file name (and after an underscore), you can use this pattern:
_(\d{8})\.pdf
And then this VB.NET line:
Regex.Match(fileName, "_(\d{8})\.pdf").Groups(1).Value
It's important to mention that Regex is by default case sensitive, so to prevent from being in a situations where "pdf" is matched and "PDF" is not, the patter can be adjusted like this:
(?i)_(\d{8})\.pdf
You can than use it directly in any expression window:
PS: You should also ensure that System.Text.RegularExpressions reference is in the Imports:
You can achieve it by this way as well :)
Path.GetFileNameWithoutExtension(Str1).Split("_"c).Last
Path.GetFileNameWithoutExtension
Returns the file name of the specified path string without the extension.
so with your String it will return to you - 10001662-1_20060301_29_1_20190301
then Split above String i.e. 10001662-1_20060301_29_1_20190301 based on _ and will return an array of string.
Last
It will return you the last element of an array returned by Split..
Regards..!!
AKsh

AKAudioFile exportAsynchronously path errors

I'm trying to use AKAudioFile.exportAsynchronously to convert wav to m4a (based on the sample code here: https://audiokit.io/playgrounds/Playback/Exporting%20Files/). I've chosen .documents as my BaseDirectory, but I just keep getting directory <my_dir> isn't valid errors — e.g.:
AKAudioFile+ProcessingAsynchronously.swift:exportAsynchronously(name:baseDir:exportFormat:fromSample:toSample:callback:):379:ERROR AKAudioFile export: directory "/var/mobile/Containers/Data/Application/20C913AD-B2F4-4F26-AAD2-0DFA0C65A886/Documents/All Of Me.mp4" isn't valid
That URL looks completely reasonable, to me, so what's up?
Okay, following #jake's tip, the solution was to handle the spaces explicitly before passing into AKAudioFile's exportAsynchronously(name:baseDir:exportFormat:callback:). I just did:
var name = String(cafURL.lastPathComponent.split(separator: ".")[0])
name = name.replacingOccurrences(of: " ", with: "%20")
let exportFile = try AKAudioFile(readFileName: "\(name).wav", baseDir: .documents)
exportFile.exportAsynchronously(name: name, baseDir: .documents, exportFormat: .m4a, callback: self.callback)

How do I find the full directory for an IFile in Cake?

I'm writing a script to produce some artefacts from my build so I want to clean up unwanted files first. I'm using CleanDirectory(dirPath, predicate).
I'm finding it disturbingly hard to work out the directory for a file. If I use GetDirectoryName() that seems to just get me the immediate parent, not the full directory path.
Func<IFileSystemInfo, bool> predicate =
fileSystemInfo => {
// Dont filter out any directories
if (fileSystemInfo is IDirectory)
return false;
var path = fileSystemInfo.Path.FullPath;
var directory = ((DirectoryPath)path).GetDirectoryName();
...
}
Obviously I can use the .NET Framework System.IO classes to do this easily but then I get strings with the slashes in the wrong direction, and things do not smoothly inter-operate with Cake which uses POSIX paths.
OK I've worked out a solution. The key to IFileSystemInfo is to try and cast the Path to various derived types/interfaces, which then provide the functionality you are probably looking for. Example:
Func<IFileSystemInfo, bool> predicate =
fileSystemInfo => {
// Dont filter out any directories
if (fileSystemInfo is IDirectory)
return false;
// We can try and cast Path as an FilePath as know it's not a directory
var file = (FilePath) fileSystemInfo.Path;
if (file.FullPath.EndsWith("Help.xml", StringComparison.OrdinalIgnoreCase))
return false;
// GetDirectory() returns a Path of type DirectoryPath
var directory = file.GetDirectory().FullPath;
...
}

C# read from a Word document

I'm trying to read from a Word document and I want the computer to tell me what is written in document not to write itself in other place. So when I say the keyword "word" my program should open a dialog menu and let me to select a word file and tell me what is inside. The other keywords work. So here's my code and also my error.
case "word":
if (openFileDialog1.ShowDialog() == System.Windows.Forms.DialogResult.OK) {
Microsoft.Office.Interop.Word.Application app = new Microsoft.Office.Interop.Word.Application();
object readFromPath = null;
Document doc = app.Documents.Open(ref readFromPath);
foreach (Paragraph objParagraph in doc.Paragraphs)
ss.SpeakAsync(objParagraph.Range.Text.Trim());
((_Document)doc).Close();
((_Application)app).Quit();
}
And my error is enter image description here
Application.Documents.Open takes the full path and filename.
The path must end with \ and prefix the string with # (or leave out the # and double the backslashes \ as one backslash is considered to be an escape character)
object readFromPath = #"C:\Users\N.Horatiu\Desktop\s.docx"
Document doc = app.Documents.Open(ref readFromPath);