Implementing Kernel32Dll.CreateFile gives "The process cannot access the file because it is being used by another process" error - c#-2.0

We have implemented following code in our app:
'SafeFileHandle handle = Kernel32Dll.CreateFile("filepath", GenericRead, Read|Write, IntPtr.Zero, Open, None, IntPtr.Zero);
It works fine when using only one app instance, but when two app simultaneously tries to load same file, it throws
"The process cannot access the file because it is being used by another process" error.
What will be appropriate use of Kernel32Dll.CreateFile in such conditions??

We have some mistake in our code which we had figured out. We need to put FILE_SHARE_READ rather Read|Write in file share. And there is also problem in another part of our code. Following is the working version:
SafeFileHandle handle = Kernel32Dll.CreateFile("filepath", GenericRead, FILE_SHARE_READ, IntPtr.Zero, Open, None, IntPtr.Zero);
Regards

Related

Swift 4 app crashes when open file from icloud

I have a problem that my app crashes when it is opening a file from iCloud. If I open this file from my app with a Document Picker, everything is fine. But if I try to open from outside my app, for example from iCloud or safari download it crashes. If I open it from local storage "my iphone" it is also working. It is interesting because it was good one week ago :)
So in AppDelegate, I've implemented the following method:
func application(_ app: UIApplication, open url: URL, options: [UIApplication.OpenURLOptionsKey : Any] = [:]) -> Bool {}
According to the logs the crash occurs because the file does not exist.
file:///private/var/mobile/Library/Mobile%20Documents/com~apple~CloudDocs/Desktop/twic1121.pgn
This is the result if I print the URL from the parameter. I think this means that the file is there.
But if i do this: print(fm.fileExists(atPath: url.path)) then this is false.
So it is obvious that after let dataFromFile = fm.contents(atPath: url.path)
this is nil.
I have no idea what could be the problem here. So the real question here is why this is nil?
It appears that the error can be many things, all not related to the class you are applying the code (AppDelegate) nor the methods you are calling.
My guess is that the URL you are calling is not correctly built (not pointing to the correct object you are trying to point to). For many reasons.
See if one of this reasons fix your issue:
(1) The end of the URL you are calling had the suffix "pgn". If you are looking to load a picture, maybe the suffix is wrong. In that case it could have been some known and supported format like "png", "jpeg" or "jpg".
(2) The "%20"symbol at the middle of your code also lifts a flag. Does not seem to be a correct URL object of swift. Maybe the URL you are using is not represented in the correct way.
(3) com~apple~CloudDocs also lifts a flag, since it would unlikely have a "~" symbol in a URL passed. This also strongly suggests that maybe the URL you are using is not represented in the correct way.
I think your URL is not pointing to where you are trying to point to, resulting in the "does exist" method return false and the loading resulting in nil.
If all of this does not fix your issue, post more details of the code. Specially what method you are calling to build/create this URL object you are using, that points to: file:///private/var/mobile/Library/Mobile%20Documents/com~apple~CloudDocs/Desktop/twic1121.pgn

Using reopened standard file descriptors in an iOS app with background capabilities?

I would like to be able to redirect my logging statements to a file so that I can retrieve them when my app runs standalone (i.e. is not attached to Xcode). I have discovered (thank you Stackoverflow) that freopen can be used to accomplish this.
If I create a new Xcode project and add the code to redirect stderr then everything works as expected.
However, when I add the redirection code to my existing, bluetooth project I am having trouble. The file is being created and I can retrieve it using iTunes or Xcode's Devices window, but it is of size 0. If I explicitly close the file then the text that I wrote actually makes it into the file. It is as though iOS is not flushing the file when the app is terminated. I suspect that the trouble stems from the fact that I have enabled background processing. Can anyone help me to understand this?
Here is my code:
let pathes = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true);
let filePath = NSURL(fileURLWithPath: pathes[0]).URLByAppendingPathComponent("Test.log")
freopen(filePath.path!, "a", stderr);
fputs("Hello, Samantha!\r\n", stderr);
struct StderrOutputStream: OutputStreamType {
static let stream = StderrOutputStream()
func write(string: String) {fputs(string, stderr)}
}
var errStream = StderrOutputStream.stream
print("Hello, Robert", toStream: &errStream)
fclose(stderr) // Without this the text does not make it into the file.
I'd leave this as a comment, but have you looked into NSFileHandle? It sounds like you just need a way to append data to the end of a text file, correct?
Once you have a handle with something like NSFileHandle(forWritingToURL:), you can use .seekToEndOfFile() and .writeData(_:). As a side note, you'll need to convert your String to Data before writing it.
Admittedly, this will probably end up being more lines of code, and you'll almost certainly need to take threading into consideration.

spreadsheetgear - open/save file

I want to update an existing Excel file using SpreadsheetGear.
I load the Excel file using:
_activeWorkbook = Factory.GetWorkbook(#"./excel/test.xls");
workbookView1.ActiveWorkbook = _activeWorkbook;
but when I want to save it:
private void menuSave_Click(object sender, EventArgs e)
{
workbookView1.GetLock();
try
{
_activeWorkbook.Save();
}
finally
{
workbookView1.ReleaseLock();
}
}
I get this error: System.IO.IOException: The process cannot access the file 'C:...\bin\Debug\excel\test.xls' because it is being used by another process.
As the exception indicates, some other process (or possibly your same application, if you utilize multiple threads) has a lock on your file and so SpreadsheetGear cannot save it back to disk. Any number of other external processes could be the culprit, such as anti-virus software scanning your file or having it open in Excel itself when you try to save it. There is no way to determine the exact cause with just the information provided above.
What I can tell you is that SpreadsheetGear does not keep any file streams open after reading and writing files. The file stream and lock on the file is only open for as long as it takes to read/write its contents, which is usually very short if the file is small. Put another way, #".excel/test.xls" should be writable immediately after your Factory.GetWorkbook(...) line executes.

For plug in running on iOS

What I want to implement is as follow:
A-app (calling app) : request the return value of a-string sent as parameter : request(a-string) -> b-string.
B-app (plug-in installed separately by me or others, it plays the role of dictionary or database ) : search a-string from database and return the result (b-string).
With successful experiences of plug-in on android and with Apple's confident rhetoric of plug-in, I thought plug-in, of course, run on iOS. After a lot of hard work, however, I finally found out:
* Note : The creation and use of loadable bundles is not supported in iOS.*
Nonetheless, not giving up, I finally made it with custom URl and pasteboard:
A-app : write a-string and false state to pasteboard & call B-app via custom URL.
B-app : viewDidLoad runs following func and thereafter exit program ; func { read pasteboard and search from database & write the result(b-string) and true state to pasteboard }
A-app : while-loop detects whether state is false or true. if true, catch b-string from pasteboard.
Anyway it works but it's too long thus almost useless. Do you have any idea for better solutions? Why doesn't Apple allow plug-in for iOS? Any responses are welcome. Thank you.
I can't answer why Apple doesn't allow plug-ins, but I can offer some advice on what you're trying to achieve.
The common pattern for sending data back to your application is to implement a callback url, so the A-app would also implement a custom URI and add that to the uri sent to B-app.
B-app would then process the uri as you have already implemented, but then instead of exiting, it simply sends the data you requested in the uri passed to it.
See http://x-callback-url.com for more details and example implementations.

XNA SoundEffect fails to be loaded from file

I got a dictionary to store SoundEffects in, like:
public static Dictionary<string, SoundEffect> Hangok = new Dictionary<string, SoundEffect>();
I load sounds from files (normal .wav format), like:
GStatic.Hangok.Add(Azonosító, SoundEffect.FromStream(File.OpenRead(Azonosító)));
, where Azonosító was the filename.
All is just fine, files are loaded, except one; an exception is created:
Operation is not valid due to the current state of the object.
, what is not much of information for me. Could anyone explain this error message OR tell me why SoundEffect.FromStream fails to read? Why? When? Workaround?
Thanks in advance:
Péter
I use the ContentManager to load in SoundEffect's. Place the wav file in the content project and it should just load in.
E.g.
SoundEffect s = Content.Load<SoundEffect>("name");
Not a complete, but working solution to this problem. "Answering my question" only, because it may be useful for other developers, who also have no idea what the problem may be.
try
{
GStatic.Hangok.Add(Azonosító, SoundEffect.FromStream(File.OpenRead(Azonosító)));
}
catch
{
GStatic.Hangok.Add(Azonosító, new SoundEffect(File.ReadAllBytes(Azonosító), 11025, AudioChannels.Mono));
}
And well: I got no idea WHY you can not load that file in the normal way and why you can load the way like in the exception handler. Having a file in mono should not be that big problem. If someone knows, please drop a note/comment.

Resources