How to get file in folder in batch process? - file

I have to get file in a folder. My process can work in Batch.
My code is this:
Io file;
FileIoPermission perm;
int handle;
Filename fileName;
[handle, filename] = WINAPI::findFirstFile( myFilePatch + "\\*.txt");
fileOpen = strFmt (myFilePatch + "\\" + filename);
if (filename)
{
perm = new FileIoPermission(filename, 'r');
perm.assert();
file = new TextIo(filename, 'r', 65001);
}
//etc... other code
// I go on to find another file
filename = WinAPI::findNextFile(handle);
fileOpen = strFmt (myFilePatch + "\\" + filename);
if (filename)
{
// open file....
}
My problem is for WinAPI.findFirstFile and WinAPI::findNextFile I have an error.
How can I search in a folder,in batch process, the files ?
Thansk all,
enjoy!

Use System.IO.DirectoryInfo and loop through the files with a for-loop. Just replace the folder path below with your folder' location, and it will generate a list of all the files inside the folder.
static void loopDirectory(Args _args)
{
System.IO.DirectoryInfo directory;
System.IO.FileInfo[] files;
System.IO.FileInfo file;
InteropPermission permission;
Filename tmpFilePath;
Filename tmpFileNameShort;
Filename tmpFileExt;
str fileNameTemp;
counter filesCount;
counter loop;
permission = new InteropPermission(InteropKind::ClrInterop);
permission.assert();
directory = new System.IO.DirectoryInfo(#"C:\Users...");
files = directory.GetFiles();
filesCount = files.get_Length();
for (loop = 0; loop < filesCount; loop++)
{
file = files.GetValue(loop);
fileNameTemp = file.get_FullName();
[tmpFilePath, tmpFileNameShort, tmpFileExt] = fileNameSplit(fileNameTemp);
info(tmpFileNameShort);
}
CodeAccessPermission::revertAssert();
}

Related

Saving and retrieving files in Codenameone

I have an app with data files (some images and xml files) i have packed them up in a zip file.
I open the file with zipme and save the files. I used this code for that
private void save1( ) {
InputStream is;
FileChooser.showOpenDialog(".zip", new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
if (e != null && e.getSource() != null) {
String file = (String)e.getSource();
FileSystemStorage fs = FileSystemStorage.getInstance();
try {
InputStream is = fs.openInputStream(file);
ZipInputStream zipStream = new ZipInputStream(is);
ZipEntry entry;
// create a buffer to improve copy performance later.
byte[] buffer = new byte[2048];
while ((entry = zipStream.getNextEntry()) != null) {
String s = entry.getName();
String outdir = FileSystemStorage.getInstance().getAppHomePath();
if (outdir.length() > 0) {
outdir = outdir ;
}
String outpath = outdir + "/" + entry.getName();
OutputStream output = null;
try {
output = FileSystemStorage.getInstance().openOutputStream(outpath);
int len = 0;
while ((len = zipStream.read(buffer)) > 0) {
output.write(buffer, 0, len);
}
} finally {
// we must always close the output file
if (output != null) {
output.close();
}
}
} } catch (IOException ex) {
Log.p(ex.getMessage(), 0); } } }});}
i see in netbeans that in the simulator the files are saved to
users/.cn1
So this works on the desktop
To fetch the image i use
String outdir = FileSystemStorage.getInstance().getAppHomePath();
Image uur1 = EncodedImage.create(outdir + "/West.jpg");
i also tried without outdir but also no luck.
What do i wrong.
This should work without the extra slash:
Image uur1 = EncodedImage.create(outdir + "West.jpg");.
Notice that this code is case sensitive so make sure the file has the right casing. Is this failing on the simulator, if so place a breakpoint on the loading code and make sure the file is physically there
The answer i found on my question is:
1 No extra slash as Shai Among suggested:
2 Make a inputstream for enecodedimage.create() instead of only a string with the path to the file
Without the second part the app doesn't run correctly in the simulation and on the device
FileSystemStorage fs = FileSystemStorage.getInstance();
String outdir = FileSystemStorage.getInstance().getAppHomePath();
String outpath = outdir + West.jpg;
InputStream isk = fs.openInputStream(outpath);
Image uur = EncodedImage.create(isk);

Copy files to folder using java 7 copy file method

Hi I need to copy the files stored in an array to a folder in the destination using java 7 copyfilemethod. I donot get any error, but it doesnt copies the files.Please help to copy the files from source to destination folder.Thanks in advance
public class copyFiles {
public static void main(String[] args) {
Date date = new Date(); // your date
Calendar cal = Calendar.getInstance();
cal.setTime(date);
int year = cal.get(Calendar.YEAR);
int month = cal.get(Calendar.MONTH);
int day = cal.get(Calendar.DAY_OF_MONTH);
String date2 = ((month+1) + "/" + (day) + "/" + year);
System.out.println("the current date is " + date2);
String path = "c://Users//Desktop//Test";
System.out.println("PATH::"+path);
File directory = new File(path);
File[] myarray;
myarray = directory.listFiles();
try{
for (int j = 0; j < myarray.length; j++) {
if(myarray[j].isDirectory()){
SimpleDateFormat sdf = new SimpleDateFormat("M/D/YY");
String dt = sdf.format(myarray[j].lastmodified());
if(dt.compareTo(date2) == 0){
File[] myarray1 - myarray[j].listFiles();
for(int i = 0; i < myarray1,length; i++){
if(myarray1[i].isDirectory()){
System.out.println("Do nothing");
}
else
{
SimpleDateFormat sdf1 = new SimpleDateFormat("M/D/YYYY");
String dt1 = sdf1.format(myarray1[i].lastmodified());
if(dt1.compareTo(date2) == 0){
System.out.println(myarray1[i]);
File Source = myarray1[i];
File Dest = new File("c://Users//Desktop//destination");
CopyFileusingJava7Files(source, dest);
}
}
}
}
}
}
}
catch(Exception e){
System.out.println("The file is not found");
}
}
Private Static void CopyFileusingJava7Files(File source, File dest) throws IOException{
Files.copy(source.toPath(), dest.toPath());
}}
Try it with administration rights. Normally a JAR doesn't have that much rights unless you define the rights you need.
I'll share some intresting links below where you can find information about defineing permissions. This is possible with a file: "MANIFEST.MF".
Manifest Basics
Defining Permissions in the mainfest

How to detect and separate concatenated files?

I am trying to find a method to separate two files that have been concatenated together using
copy /b file1+file2 file3.
I know the mime type and file type of at least one of the two files.
With the following csharp code you can do the split based on the fact that the zip file has the signature of 4 bytes that indicates the local file header. This code will break if the EXE has the same 4 bytes some where. If you want to conquer that you have to dig through the PE/COFF header to add up all section sizes
And NO, it is not very efficient to copy a stream byte by byte...
using(var fs = new FileStream(#"exeandzip.screwed", FileMode.Open))
{
var lfh = new byte[] { 0x50, 0x4b, 0x03, 0x04 }; /* zip local file header signature */
var match = 0;
var splitAt = 0;
var keep = new Queue<int>();
var b = fs.ReadByte();
using(var exe = new FileStream(
#"exeandzip.screwed.exe",
FileMode.Create))
{
while((b != -1) && (match<lfh.Length))
{ splitAt++;
if (b==lfh[match])
{
match++;
keep.Enqueue(b);
}
else
{
while(keep.Count>0)
{
exe.WriteByte((byte) keep.Dequeue());
}
exe.WriteByte((byte)b);
match=0;
}
b = fs.ReadByte();
}
}
if (match==lfh.Length && b!=-1)
{
keep.Enqueue(b);
splitAt = splitAt-lfh.Length;
Console.WriteLine(splitAt);
using(var zip = new FileStream(
#"exeandzip.screwed.zip",
FileMode.Create))
{
while(keep.Count>0)
{
zip.WriteByte((byte) keep.Dequeue());
}
b = fs.ReadByte();
while(b != -1)
{
zip.WriteByte((byte)b);
b = fs.ReadByte();
}
}
}
}
Or u can use foremost -i <input file> -o <output directory>
I've even split the apple webarchive format file in this way

Could not find a part of the path using File.Copy(source,destination,true) in C# console app

I continue to get the (Could not find a part of the path 'C:\Users(user profile)\VirtualStore\Program Files (x86)\E!PC\Macros) exception. The directory is there on the drive but im not sure why i continue to get this exception.
Extra6DestPath = "C:\Users\(user profile)\VirtualStore\Program Files (x86)\E!PC\Macros\"
static void copyMacrosAndBitmaps(string ExtraSourcePath, string Extra6xDestPath )
{
//counter for total Macro count on network
int Count = 0;
//counter for total bitmap count on network
int iCount = 0;
//Get File information to use for copy
FileInfo[] macrosArray;
FileInfo[] iconArray;
//Get Directory information to use for copy
DirectoryInfo di = new DirectoryInfo(ExtraSourcePath);
DirectoryInfo diIcon = new DirectoryInfo(ExtraIconPath);
//set all macro paths as a string from directory into an array
macrosArray = di.GetFiles("*.ebm");
Count = macrosArray.Length;
//set all bitmaps from directory into an array
iconArray = diIcon.GetFiles("*.bmp");
iCount = iconArray.Length;
//copy macros into destination folder
if (Count == 0)
{
throw new FileNotFoundException("No Macros found to copy");
}
else
{
for (int i = 0; i < Count; i++)
{
File.Copy(Extra6xSourcePathW7 + macrosArray[i].ToString(), Extra6xDestPath + iconArray[i].Name, true);
}
//Copy the bitmaps into destination folder
if (iCount == 0)
{
throw new FileNotFoundException("No bitmaps found to copy");
}
else
{
for (int i = 0; i < Count; i++)
{
File.Copy(ExtraIconPath + iconArray[i].ToString(), Extra6xDestPath + iconArray[i].Name, true);
}
}
}
}
I would first try declaring the path with # symbol, to handle characters that need to be escaped:
Extra6DestPath = #"C:\Users\(user profile)\VirtualStore\Program Files (x86)\E!PC\Macros\"

How to get the Directory name/path from an opened handle

On opening a directory via zwopenfile(open directory option), it returns a handle for the directory path. Now I need to get the directory path from the handle. Its my requirement.
I could see an example(please see the code below) where file name can be fetched from file handle. But the below example does not help for directory. Is there any possibilities in fetching directory name from its opened handle.
CHAR* GetFileNameFromHandle(HANDLE hFile)
{
BOOL bSuccess = FALSE;
TCHAR pszFilename[MAX_PATH+1];
HANDLE hFileMap;
// Get the file size.
DWORD dwFileSizeHi = 0;
DWORD dwFileSizeLo = GetFileSize(hFile, &dwFileSizeHi);
if( dwFileSizeLo == 0 && dwFileSizeHi == 0 )
{
printf("Cannot map a file with a length of zero.\n");
return FALSE;
}
// Create a file mapping object.
hFileMap = CreateFileMappingW(hFile,
NULL,
PAGE_READONLY,
0,
1,
NULL);
if (hFileMap)
{
// Create a file mapping to get the file name.
void* pMem = MapViewOfFile(hFileMap, FILE_MAP_READ, 0, 0, 1);
if (pMem)
{
if (GetMappedFileNameW (GetCurrentProcess(),
pMem,
pszFilename,
MAX_PATH))
{
// Translate path with device name to drive letters.
TCHAR szTemp[1024];
szTemp[0] = '\0';
if (GetLogicalDriveStrings(1024-1, szTemp))
{
TCHAR szName[MAX_PATH];
TCHAR szDrive[3] = TEXT(" :");
BOOL bFound = FALSE;
TCHAR* p = szTemp;
do
{
// Copy the drive letter to the template string
*szDrive = *p;
// Look up each device name
if (QueryDosDevice(szDrive, szName, MAX_PATH))
{
UINT uNameLen = _tcslen(szName);
if (uNameLen < MAX_PATH)
{
bFound = _tcsnicmp(pszFilename, szName, uNameLen) == 0;
if (bFound && *(pszFilename + uNameLen) == _T('\\'))
{
// Reconstruct pszFilename using szTempFile
// Replace device path with DOS path
TCHAR szTempFile[MAX_PATH];
StringCchPrintf(szTempFile,
MAX_PATH,
TEXT("%s%s"),
szDrive,
pszFilename+uNameLen);
StringCchCopyN(pszFilename, MAX_PATH+1, szTempFile, _tcslen(szTempFile));
}
}
}
// Go to the next NULL character.
while (*p++);
} while (!bFound && *p); // end of string
}
}
bSuccess = TRUE;
UnmapViewOfFile(pMem);
}
CloseHandle(hFileMap);
}
_tprintf(TEXT("File name is %s\n"), pszFilename);
return( pszFilename);
}
NtQueryObject did it.
The example from MSDN, which you posted, gives a 'fully qualified' file name, i.e. with the drive letter and the full path.
With that, it should be easy to get the directory name: just strip off everything after the last \.

Resources