Click here to Skip to main content
15,895,011 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi Coders,
How can I check if a file say "C:\abc.xls" file is already open or not, if yes then how to close it.

Problem: The problem I am facing is: My code crashes When I try to write a file which is already open, how can I solve it? Answer to my question above will be a part of solution to my problem

Thanks in advance
Deepak
Posted
Updated 18-Aug-10 23:21pm
v2
Comments
Eugen Podsypalnikov 19-Aug-10 4:53am    
Could you post the code part, that "crashes", please ? :)
deepakkumargautam 19-Aug-10 5:20am    
workbook = excel->Workbooks->Add(static_cast<long>(Excel::xlWorksheet)); // Create the workbook
worksheet = excel->ActiveSheet; // Get the active sheet

//some code//

worksheet->SaveAs(_strPath); // here comes the error when I try to save an
// excel file alraedy open
Emilio Garavaglia 19-Aug-10 5:21am    
Retagged as C++/CLI

Hi,

you can check the file mode using the following code:
try
                {
//Verify whether the file opens in write mode
                    using (Stream stream = File.Open(e.FullPath, FileMode.Open, FileAccess.ReadWrite, FileShare.ReadWrite))
                    {
                        if (stream != null)
                        {
                       // File is available for write.
                            break;
                        }
                    }
                }
                catch (FileNotFoundException ex)
                {
                //The file is not found.
}
                catch (IOException ex)
                {
                    //File is undergoing some operation. May be write or copy, etc
                }
                catch (UnauthorizedAccessException ex)
                {
                    //the User is not authorised to use the file
                }
 
Share this answer
 
Comments
Emilio Garavaglia 19-Aug-10 5:19am    
Reason for my vote of 2
The OP tagged as C , not C /CLI. And this is C /CLI
Emilio Garavaglia 19-Aug-10 5:20am    
I see right not the answer had been accepted.
I revote and change the question tag.
deepakkumargautam 19-Aug-10 5:34am    
Hi Shiva,
Thanks for replying, I have embed the code but getting some errors. I guess I need to #include something ? specially for stream and FILE?
: I have accepted the answer, I am new @ codeproject so don't know much.

Thanks
shiva's answer is almost there. When you try to open the file, use FileShare.None. If the file is already open, attempting to open the file with FileShare.None with throw an exception that you can react to.
 
Share this answer
 
Hi,

Just add

using System.IO;
 
Share this answer
 
Comments
deepakkumargautam 19-Aug-10 6:00am    
Done that Shiva but stil getting some errorrs "steam underclared undentifier, same for FILE " ?
shivaprasadk 19-Aug-10 6:16am    
Deepak, it is better, if you post the code which is throwing error.
deepakkumargautam 19-Aug-10 6:34am    
void g_fnWriteExcelFile(CSite *_objSite,char *_strPath)
{
char Range[7],bufCtr[10];
CString _strOutputName;
CoInitialize(NULL);
Excel::_WorkbookPtr workbook ;
Excel::_ApplicationPtr excel;
Excel::_WorksheetPtr worksheet ;
try
{
Excel::_ApplicationPtr excel ;
// Initialize Excel and make sure it's initialized
HRESULT hr = excel.CreateInstance(L"Excel.Application");
if(FAILED(hr))
{
return ;
}


workbook = excel->Workbooks->Add(static_cast<long>(Excel::xlWorksheet)); // Create the workbook
worksheet = excel->ActiveSheet; // Get the active sheet


//tempstrPath = (char*)malloc(sizeof(_strPath));
_strOutputName = _objSite->m_strPrefix + "_" + "MappingResult";
worksheet->Name=(_bstr_t)_strOutputName;

strcat(_strPath,"\");

_strOutputName = _strOutputName + ".xlsx"; // excel 2007
strcat(_strPath,_strOutputName) ;



_variant_t var;

CDevice *_objDevice = _objSite->m_objDevice;
CDevicePoint *_objDevicePoint = NULL;

///////////////////////////////Header Start/////////////////////////////////////////
int nCounter = 1;

while(_objDevice!=NULL)
{
_objDevicePoint = _objDevice->m_objDevicePoint;
while(_objDevicePoint!=NULL)
{
if(nCounter == 2)
{
CString tempColor = "15" ;

strcpy(Range,"A");
itoa(nCounter,bufCtr,10);
strcat(Range,bufCtr);
worksheet->Range[Range]->Value2 = "Tag Name";
_objDevicePoint = _objDevicePoint->next ;
}
nCounter++;

}
_objDevice = _objDevice->next ;
}
worksheet->SaveAs(_strPath); // saving workshee
workbook->Close(); // Close the workbook
excel->Quit(); // Quit excel
}
catch(_com_error &ce)
{
// Handle the error
AfxMessageBox(ce.ErrorMessage()) ;

}
CoUninitialize();
}

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900