Monday, February 22, 2010

How to check if file exists in dos or not?

-- xp_cmdshell

declare @Path varchar(128) , @FileName varchar(128)
select @Path = 'C:\Temp\' , @FileName = 'file.txt'
declare @cmd varchar(1000)

create table #File(s varchar(1000))
select @cmd = 'dir /B ' + @Path + @FileName

insert #File exec
master.dbo.xp_cmdshell @cmd

if exists (select * from #File where s = @FileName)
print 'exists'
else
print 'not exists'
drop table #File


-- using xp_fileexists
declare @Path varchar(128) , @FileName varchar(128)
select @Path = 'C:\Temp\' , @FileName = 'file.txt'

declare @i int
declare @File varchar(1000)

select @File = @Path + @FileName

exec master.dbo.xp_fileexist @File, @i out

if @i = 1
print 'exists'
else
print 'not exists'

2 comments:

  1. Exactly what I was looking for and it works like a charm.
    Thank you!
    PEC

    ReplyDelete