I'm using FileStream to read files in two computers that are connected in a Local Area Network (LAN). I have no problem to read the files when the others computers are connected. I'm checking if the directory exists before writing the file I'm checking if the directory AND the file exists before reading the file.
file_pc1 = new File("//OTHER-PC/Folder/file.csv");
directory = new File("//OTHER-PC/Folder");
if (directory_pc1.exists)
{
stream.open(file_pc1, FileMode.WRITE);
stream.writeUTFBytes(csv.data);
stream.close();
}
if (directory_pc1.exists && file_pc1.exists)
{
stream.open(file_pc1, FileMode.READ);
stream.writeUTFBytes(csv.data);
stream.close();
}
All this works great but if the other computer is not connected, the statements directory_pc1.exists and file_pc1.exists takes a very long time and the app freezes, sometime even sending the "Application is not responding" message from Windows, but it finally responds after a long time.
Is there a fastest way to check if i'm connected to another PC?
While I don't know of a method to make
File.exists()
perform faster (likely there is no way as it's more of an OS issue), you can at least mitigate the issue by using asynchronous operations instead - thus avoiding locking the UI.You can skip the exists operation, and just attempt to open the file async, if it errors, then you know the file doesn't exist and it will likely take about the same amount of time as using
File.exists
.So something like this:
That all said, since your just writing a file, it doesn't actually make sense to even check if it exists or not (unless you need to use the current data in that file as part of your write operation) - if you used
FileMode.WRITE
, it doesn't matter if the file exists or not it will attempt to save the file. You'll need to wrap it in a try catch though in case the network location is unavailable.